I have a Partial View that returns a Javascript function call after I submit an Ajax form. It takes a list of addresses and call Javascript functions to geocode and place markers on a Google Map. When I compile the following code, I get "Conditional compilation is turned off" error around var in the ForEach line.
@model IEnumerable<TestStore.Models.Address>
@if (Model.Count() > 0)
{
<script type="text/javascript">
deleteMarkers();
@foreach(var item in Model)
{
codeAddress('@item.GetAddress');
}
</script>
}
I fiddle around with the code and the following does work without compile errors:
@if (Model.Count() > 0)
{
<script type="text/javascript">
deleteMarkers();
</script>
foreach (var item in Model)
{
<script type="text/javascript">
codeAddress('@item.GetAddress');
</script>
}
}
For sake of discussion, if I have longer logic that make a lot of Javascript function calls inside loops, I would much prefer to surround everything inside 1 script block. I searched around Stack Overflow and it seem that Razor syntax could go inside a script block but I don't know how that look like in my example.
You can't. Razor is a . NET assembly and doesn't run on JavaScript or in a browser. It's meant to be executed server-side.
A Razor Page is almost the same as ASP.NET MVC's view component. It has basically the syntax and functionality same as MVC. The basic difference between Razor pages and MVC is that the model and controller code is also added within the Razor Page itself. You do not need to add code separately.
Razor is a simple programming syntax for embedding server code in web pages. Razor syntax is based on the ASP.NET framework, the part of the Microsoft.NET Framework that's specifically designed for creating web applications.
Razor markup is code that interacts with HTML markup to produce a webpage that's sent to the client. In ASP.NET Core MVC, views are .cshtml files that use the C# programming language in Razor markup.
Or you can use the @:
syntax instead of the <text>
element in your loop. Here is a tutorial.
@:codeAddress(@item.GetAddress);
its because the javascript inside your for loop looks like C# code to Razor. Wrap it in <text>
. In general any block content { /* this is block content */ }
should always have a single html node - or if you dont need an html node (like in your case) you can use <text>
@foreach(var item in Model)
{
<text>codeAddress('@item.GetAddress');</text>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With