Reputation: 1396
I have code like this in my Razor view
<script>
var JsModel = @Html.Raw(Json.Encode(CsModel));
</script>
This works just fine. It converts the C# model received from the controller to a JS object, which is later used to populate Google Map with markers and various other stuff.
The problem is, Visual Studio is showing a big red syntax error in this line, and it's driving me insane. The code is perfectly fine, model is always non-null, and the encoding always works. But Razor parser, or perhaps even R#, I'm not sure which, trips up on it, as it seems to ignore C# code. So what it sees is just var JsModel = ;
and complains.
Any way for me to tell it that it's ok? What can I do here?
Upvotes: 2
Views: 980
Reputation: 1396
We can get around this by putting raw json into quotes, and thus tricking the parser, and then using JQuery eval (or any other eval you prefer) to convert string into an object.
<script>
var JsModel = $.parseJSON('@Html.Raw(Json.Encode(CsModel))');
</script>
Upvotes: 2
Reputation: 11721
Use function as shown below :
function SetMyValue(value){
return value;
}
var JsModel = SetMyValue(@Html.Raw(Json.Encode(CsModel)));
As documented here http://msdn.microsoft.com/en-us/library/gg480740(v=vs.118).aspx:-
This method wraps HTML markup using the IHtmlString class, which renders unencoded HTML.
The Razor escaping system will not escape anything of type IHtmlString. The Html.Raw() method simply returns an HtmlString instance containing your text.
So wrapping it into function and returning from there would work for you.
Upvotes: 1
Reputation: 18873
<script>
var JsModel = '@Html.Raw(Json.Encode(CsModel))'; //apply single quotes as shown
</script>
Upvotes: 1