How to remove invalid syntax error message in editing Razor view

1.9k views Asked by At

In Razor ( in site master page and in views) javascript strings with dynamic content are used, like

@inherits ViewBase<EntityBase>

<script type="text/javascript">
  $(function () {
    $("#xx").attr('title', @Html.Raw(Json.Encode("<>.")));

Microsoft Visual Studio Express for Web 2012 flags trailing parenthese as error:

syntaxerror

How to fix this ?

Construction ´@Html.Raw(Json.Encode(Res.I("somestring")))´ is used in may places to dynamically translate texts for javascript. I() returns text im user languge. How to create some helper so that code is simllifid ? I created view common base class and added function there so that view contains only I("somestring") but this is not available in Razor master layout file Site.cshtml specified in ´Layout = "~/Views/Shared/Site.cshtml"´

How to fix this error and use simple function I("somestring") which returs encoded javascript string ?

ASP.NET MVC3 , C#, jquery, jquery ui are used.

2

There are 2 answers

2
SLaks On BEST ANSWER

Visual Studio's Javascript language service does not recognize Razor markup within Javascript code blocks.
These errors are false positives, and will not occur at runtime.

0
Nolonar On

Instead of writing

@Html.Raw(Json.Encode("<>."))

you can write

"@Html.Raw(Json.Encode("<>."))"

Unfortunately, this only works if you need a string. I haven't yet found a way to circumvent those false positives for other data types like int or bool, short of casting them:

var myInt = Number("@myInt");
var myFloat = Number("@myFloat");

or in the case of boolean, checking their value for "true":

var myBool = "@myBool".toLowerCase() === "true";