Can we Assign Javascript variable value to Razor Syntax Variable?
like.
var Javascript-variable=$("#test").val();
#html.Actionlink("User","Index",new {Id='Javascript-variable'})
Can we Passing Java script variable value to Razor Syntax Variable?
No, because JavaScript used in this context executes on the client, whereas Razor code executes on the server. For practical purposes, they have no relation.
But I imagine that you want to use the routing capabilities provided on the server from within JavaScript, and that is possible. We can use Razor to generate JavaScript.
Embed the ActionLink() call into a JavaScript snippet.
Render the URL structure on the server, using the ActionLink() method which is route-aware.
Get a value on the client.
Insert the value into the URL structure.
One way to do that is to render the link with a placeholder value, which is later replaced using JavaScript.
var url = '#Html.ActionLink("User","Index",new { Id = 0 })';
var id = $("#test").val();
var mergedUrl = url.replace(/0$/, id); // replace the 0 with a real ID
Related
I have a project where I am passing the data from C# to cshtml by something like this:
public IActionResult Index()
{
ViewData["temp"] = "abc"
return View();
}
This value is then received in the cshtml file where I can read this as
var temp = ViewData["temp"];
I have a typescript file that is then booted from this cshtml file.
My question is, how can I use this temp variable in my typescript code. I don't want to create a 'div' element for this temp data and then read its value in typescript as this will not be a clean thing to do from security perspective.
Can you please suggest some way to do it in a proper way?
In your view returned by the Index action just choose an existing element (you can choose the body element if your view contain it) and in that element add an data-* attribute (you can name it data-temp) like below :
<SomeElementInMyView data-temp="#temp">...</SomeElementInMyView>
In your Typescript file, I suppose you're using jQuery so get the data value like this:
let dataTemp = $("SomeElementInMyView").data("temp");
You can pass it as string variable in html eg.
let typeScriptVariable: string = "#temp";
I'm having trouble accessing localizations, the value always appears in the default language.
I have two resource files in App_GlobalResources:
Resource.resx contains a string with the name "Hello" and the value of "World".
Resource.fr.resx contains a string with the name "Hello" and the value of "Monde"
In my Razor template:
<lang:string key="Resource, Resources.Resource.Hello" xmlns:lang="http://www.composite.net/ns/localization/1.0" />
"World" is always displayed, never "Monde", even when viewing the page in French.
In a vanilla asp.net website template, with the same resources, the following code within a Razor template displays "Monde"
String cultureInfo = "fr-CA";
System.Threading.Thread.CurrentThread.CurrentCulture =
System.Globalization.CultureInfo.CreateSpecificCulture(cultureInfo);
System.Threading.Thread.CurrentThread.CurrentUICulture = new
System.Globalization.CultureInfo(cultureInfo);
Response.Write(ObjectInfo.Print(Resources.Resource.Hello));
However, within C1 it results in "World".
How should I be going about this?
Thanks!
The <lang:string construct is mainly meant for XSLT templates and functions where you can't as easily fallback to calling c# code directly as in Razor.
Have you tried printing out the resource on your Razor template like this instead #Resources.Resource.Hello ?
I have the requirement to use Html.RenderAction like you would in ASP.NET MVC.
For instance I have a Home Page with News and Products on.
I would like to do for instance
#Html.RenderAction("/api/products/featured")
Which would start a new service call and output the template to the html stream.
Is this possible using ServiceStack Razor and if so how do I accomplish it?
The PartialExamples.cshtml test page shows different examples of rendering a razor view inside a page, e.g:
Using the new RenderToAction() method which lets you execute a Service and it's rendered partial view with a route and QueryString, e.g:
#Html.RenderAction("/products/1")
This also takes an optional view name if you want a different view than the default:
#Html.RenderAction("/products/1", "CustomProductView")
There's also the normal Html.Partial() to specify which view and model you want to render in the page, e.g:
#Html.Partial("GetProduct",
base.ExecuteService<ProductService>(s => s.Any(new GetProduct { Id = 1 })))
ExecuteService is simply a wrapper around the equivalent ResolveService in a using statement, i.e:
#{
Response response = null;
using (var service = base.ResolveService<ProductService>())
{
response = service.Any(new GetProduct { Id = 1 });
}
}
#Html.Partial("GetProduct", response)
The new RenderToAction() method in Razor Views was added in v4.0.34+ which is now available on MyGet.
*I may be duplicating my answer or I lost it somehow
Looking at the ServiceStack.Razor.ViewPage class there is an Html property of type ServiceStack.Html.HtmlHelper. I don't see 'RenderAction' as a method (or extension method) on this class so it doesn't appear to be available. There is a 'Partial' method that takes the ViewName and an overload that takes a ViewName and an object. Based on your above comment this doesn't appear to be a useful solution.
If I'm correct about the above, I think you'd need your 'Featured View Template' to pull in the data. Could add soemthing like
{ FeaturedResponse products = new JsonServiceClient("http://localhost").Get<FeaturedResponse>("/api/products/featured"); }
to your template. This would allow you to use the products variable like a Model.
Or, use JavaScript to pull the data into the template. You would have have to use JavaScript to get your data into the HTML elements, though.
You could then render the template using #Html.Partial('Featured')
Hope this helps.
lets say I want to a partial view like the following sample
#Html.RenderAction("ListDocuments", "MultiFileAttachments", new { id = jsparameter });
in the jsparameter I want to pass as a parameter that is the result of a javascript function. Maybe this is not logical because javascript runs on the client, but how can I achieve a similar functionality ? thank you in advance
If you need to call a part of a page based on some actions or values determined by actions on the client side, then you should think to use JavaScript (preferably jQuery) and Ajax.
Through jQuery-Ajax, you could easily call a Partial view through the Contoler and since it's a regular HTTP request, you would be able to pass all the parameters you need.
Using code as :
#Html.RenderAction("ListDocuments", "MultiFileAttachments", new { id = jsparameter });
is not possible since it is rendered by the server before it's sent to the client browser.
I am using ViewBag value as follows :
var date = "#ViewBag.fromDateForEditMode"
$('#FromDate').val(date);
All I am getting is #ViewBag.fromDateForEditMode and no value.
The Razor engine doesn't execute when MVC is rendering an HTML file, so nothing will parse #ViewBag.fromDateForEditMode and replace it with the ViewBag property value :)
The problem that you are having is that you are trying to enclose the #ViewBag.fromDateForEditMode in quotes. When you do that within your jquery function, this causes the browser jquery processor to evaluate it as a literal string at the time the script is called, rather than allowing your razor engine to evaluate the ViewBag contents at the time the page is loaded.
To get around this issue, use:
var startDate = new Date(#ViewBag.StartDate.Year.ToString(), #ViewBag.StartDate.Month.ToString() -1, #ViewBag.StartDate.Day.ToString());
This will allow the razor engine to evaluate the ViewBag contents before the jquery script is executed.