Razor/JavaScript and trailing semicolon

2019-01-09 00:10发布

Using Visual Studio 2012, on a Razor view page, in the JavaScript section, I am getting what I think is a battle between Razor syntax vs JavaScript syntax. In particular, the trailing semicolon in the script section is flagged by intellisense and a compiler warning (not error) is delivered:

'Warning 13 Syntax error'.

If I remove it, then I get a statement termination recommendation (ReSharper in this case, but just good practice).

<script type="text/javascript">
    $().ready(function(){
        var customer = @Html.Raw(ViewBag.CustomerJSON);  // <- Razor (I think) doesn't like this semicolon
    });
</script>

Is this a bug in Razor? If so, is there a way I can rewrite this to avoid this issue?

7条回答
聊天终结者
2楼-- · 2019-01-09 01:05

I found that wrapping the Razor syntax in a JavaScript identity function also makes the IDE happy.

<script type="text/javascript">
    @* I stands for Identity *@
    function I(obj) { return obj; }
    $().ready(function(){
        var customer = I(@Html.Raw(ViewBag.CustomerJSON));
    });
</script>
查看更多
登录 后发表回答