Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 4 - Razor Within Javascript Function Within @Section Causes Scope Error

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.

like image 637
Scott Coates Avatar asked Dec 27 '11 19:12

Scott Coates


People also ask

Can I use Razor code in JavaScript in ASP NET MVC?

Solution 1. You can't. Razor is a . NET assembly and doesn't run on JavaScript or in a browser.

Can I use JavaScript in Razor pages?

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.

Where do you put JavaScript on a Razor page?

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.


1 Answers

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

like image 134
Lski Avatar answered Oct 26 '22 23:10

Lski