Michael
Michael

Reputation: 13636

Why quots encoded in JSON in razor view page?

I am newer in web programming and in asp.net mvc4, so maybe my question will seem naive to some of you. I am passing JSON with help of @ViewBag.

I parse JSON in razor view page using this rows:

var strJson = '@ViewBag.Json';  
var strDecoded = strJson.replace(/"/g, '"'); 
var JSONParsed = strDecoded.parse();

Here is row in my controller class that creates JSON:

ViewBag.Json = new JavaScriptSerializer().Serialize(contacts);

Evrething works fine,my question about this row:

strJson.replace(/"/g, '"'); 

Before I sent the JSON to the razor view page I see quots not encoded, but in JSON in razor view page I see quots encoded(").

Why I get quots encoded in JSON in razor view page?

Thank you in advance.

Upvotes: 0

Views: 128

Answers (1)

SLaks
SLaks

Reputation: 887937

Razor autmatically HTML-encodes all text that you output.
You can prevent this by calling Html.Raw().

Also, JSON is already valid Javascript; there is no need to parse a string:

var jsonParsed = @Html.Raw(ViewBag.Json);

Upvotes: 2

Related Questions