Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net MVC3 RC Razor views : syntax for embedding code inside <javascript> block

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>
like image 944
rekna Avatar asked Nov 17 '10 13:11

rekna


People also ask

What is the syntax for server side comment in razor view?

Razor View Engine has two types of comments, one is single-line and another is multiline. Razor uses the syntax "@* .. *@" for the comment block but in a C# code block we can also use "/* */" or "//".

Which of the following Razor syntax allows you to explicitly indicate the start of content?

Using @: to explicitly indicate the start of content.

What is Razor syntax in ASP.NET MVC?

Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine.

Which Razor syntax is used to add server side?

Razor now allows you to wrap any code/content/region of a view within a @* comment *@ syntax (which works for both C# and VB templates).


2 Answers

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.

like image 170
Darin Dimitrov Avatar answered Nov 18 '22 07:11

Darin Dimitrov


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> 
like image 36
James H Avatar answered Nov 18 '22 08:11

James H