The problem is that placing a C# variable within a JS function within a @Section produces incorrect javascript (in MVC 4 only).
In a JS function in MVC 3, everything executes as expected.
@section test {
<script type="text/javascript">
$(function () {
alert(@DateTime.Now);
});
</script>
}
Take this exact same code and place it in an MVC4 app and you will get malformed JS.
The HTML on the page will actually render the following:
<script type="text/javascript">
$(function () {
alert(12/27/2011 11:04:04 AM);
and the html will emit
); }
Note the closing script tag is not produced.
It appears the closing curly brace in the JS function is confused the be the closing curly brace in Razor.
Note that I am also declaring a RenderSection("test",false") in my _Layout.cshtml file.
Solution 1. You can't. Razor is a . NET assembly and doesn't run on JavaScript or in a browser.
You can call JavaScript methods from the Blazor pages with the help of JavaScript Interop by injecting the dependency IJSRuntime into the razor page. Then refer the script in the HTML page of the blazor application. Check this link for more information.
Calling JavaScript Function from Razor View To include a JavaScript function, it is as simple as include a <script> tag and define the function inside the script block.
Slightly old reply, but I was experiencing the same issue, soI have submitted a feedback report on Microsoft.Connect hopefully it should get sorted before full release.
https://connect.microsoft.com/VisualStudio/feedback/details/720079/mvc-4-javascript-in-section-issue
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