5
votes

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.

6
wow, this post made me found out about mvc4... - Shawn Mclean

6 Answers

4
votes

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

4
votes

I know have been a wile since the question was asked, but you can also try something like this.

@section test {
    <script type="text/javascript">
        $(function () {
            alert(@(DateTime.Now));
        });
    </script>
}

Note the "()" after the @.

Hope this help.

3
votes

Sorry, I just couldn't help but chime in here... I don't see how the syntax in the initial question would actually work. When I try it in MVC3, in VS2010, it puts a green squiggly line under the "DateTime", and when you hover over that, it says "Conditional compilation is turned off". But if I surround it in quotes, it does work, as in:

@section test {

<script type="text/javascript">
    $(function () {
        alert("@DateTime.Now");
    });
</script>
} 

And then when I run it (F5) it displays the JavaScript alert as expected, and when I view source it renders:

<script type="text/javascript">
    $(function () {
        alert("07/09/2012 10:41:26");
    });
</script>
2
votes

What I ended up doing for now was emitting the closing JS func in @Html.Raw().

Since this is so easy to recreate, I'm going to submit this as a bug to Microsoft.

@section test {
    <script type="text/javascript">
        $(function () {
            alert(@DateTime.Now);
        @(Html.Raw("});"))
    </script>
}
1
votes

I've seen problems like this. Wrap your alert statement in <text></text> tags

0
votes

Definitely a bug. I prefer this workaround over the one you posted. For some reason, other razor elements seem to interpret the brackets correctly, so I simply wrap the script content in another set of braces.

@section test {
if (true) {
<script type="text/javascript">
    $(function () {
        alert(@DateTime.Now);
    });
</script>
}
}