What this code does?
@model CourseVM
<script type="text/javascript">
var model = @Html.Raw(Json.Encode(Model));
// go ahead and use the model javascript variable to bind with ko
</script>
Json.Encode serialises the Model to a JSON string. Html.Raw ensures that it is rendered verbatim and isn’t HTML-encoded by Razor. If it is Html-encoded (which Razor does by default) special characters will be converted to their HTML entity representations (e.g. & becomes &). Then the JSON string might not be valid JSON.
There are arguments that encoding protects against script injection and Html.Raw removes that protection.
Html encode() is a built-in feature in MVC so we shouldn’t be worried about script injection in MVC.
Add to favorites