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>
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 "//".
Using @: to explicitly indicate the start of content.
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.
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).
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With