Asp.Net MVC3 RC Razor views : syntax for embedding

2019-02-08 01:43发布

问题:

Having trouble embedding c# code inside a javascript block with MVC3 RC1 razor view. What syntax should I use to make this working? I get warnings eg. Expected constant on the isOk variable among other. (Without text tag, the following code is not recognized as javascript)

@{bool isOk = true;}

<script type="text/javascript">
    var tmp1 = "";
    @if (isOk)
    { 
        <text>
            var tmp=""; // this should be interpreted as javascript
        </text>       
    }
</script>

回答1:

You need the <text> tag to indicate that the contents is not evaluated on the server. For example:

@{
    var isOK = true;
}

<script type="text/javascript">
    var tmp1 = "";
    @if (isOK)
    { 
        <text>
            var tmp = "foo";
        </text>       
    }
</script>

will output in the resulting page:

<script type="text/javascript">
    var tmp1 = "";
    var tmp = "foo";
</script>

As far as the Expected Constant warning is concerned, well, Razor Intellisense is still in beta so it's far from perfect. It's just a warning you can safely ignore. The important thing is what is that the application works and emits valid HTML. Hope this is something that will be fixed in the final product. From personal experience the only warnings I trust are the one emitted by the C# compiler. When I am working in a view I safely ignore all the crappy warnings that Visual Studio emits because I know that it is wrong.



回答2:

An alternative (more terse and easier to read IMO) is to escape back out to text as follows:

<script type="text/javascript"> 
    var tmp1 = ""; 
    @if (isOK) 
    {  
        @:var tmp = "foo";
    } 
</script>