Asp.net-mvc – ASP.NET MVC 4 – Razor Within Javascript Function Within @Section Causes Scope Error

asp.net-mvcrazor

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.

Best Answer

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