Skip to content Skip to sidebar Skip to footer

Razor Syntax Error Serializing Asp.net Model To Json With Html.raw

This line is giving me a syntax error in Visual Studio 2012 (literally just 'Syntax Error'): var data = @Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Seriali

Solution 1:

Using function

Implement a simple JavaScript set function that returns input argument:

functionset(value){
    return value;
}

Use this function to assign Razor model value to a JavaScript variable:

vardata = set(@Json.Encode(Model));

As an option you can use self-calling function:

vardata = function() { returnset(@Json.Encode(Model)); }();

Solution 2:

Try to wrap it within a function as follows:

vardata = function() { return@Html.Raw(Json.Encode(Model)); }();

Solution 3:

Use JSON.Net, instead of either the JavaScriptSerializer or DataContractJsonSerializer, to avoid the nightmare that is JSON Dates:

vardata = function () { 
    return@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model)); }();

Solution 4:

Even easier!! This will fix that little annoyance:

varmodel= [@Html.Raw(Json.Encode(Model))][0];

Basically intellisense wants something around @Html.Raw. There is actually nothing wrong but we have to handle the intellisense shortcoming. Here we declare the result as the first index of a new array, then return the first index.

FYI: If you want your model to reflect changes to the DOM then try the JSModel class.

Solution 5:

You don't need to write any new javascript functions, just wrap the code into brackets

vardata = (@Html.Raw(Json.Encode(Model)));

works for me in Visual Studio 2015, not sure about VS2012

Post a Comment for "Razor Syntax Error Serializing Asp.net Model To Json With Html.raw"