Razor Syntax Error Serializing ASP.NET Model to JSON with HTML.Raw

Razor syntax error serializing ASP.NET Model to JSON with Html.Raw

Using function

Implement a simple JavaScript set function that returns input argument:

function set(value){
return value;
}

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

var data = set(@Json.Encode(Model));

As an option you can use self-calling function:

var data = function() { return set(@Json.Encode(Model)); }();

How to get JSON object from Razor Model object in javascript

You could use the following:

var json = @Html.Raw(Json.Encode(@Model.CollegeInformationlist));

This would output the following (without seeing your model I've only included one field):

<script>
var json = [{"State":"a state"}];
</script>

Working Fiddle

AspNetCore

AspNetCore uses Json.Serialize intead of Json.Encode

var json = @Html.Raw(Json.Serialize(@Model.CollegeInformationlist));

MVC 5/6

You can use Newtonsoft for this:

    @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model, 
Newtonsoft.Json.Formatting.Indented))

This gives you more control of the json formatting i.e. indenting as above, camelcasing etc.

Javascript syntax error in razor page

You might try enclosing it in a block:

var serializedData = @{ 
Html.Raw(NewtonSoft.Json.JsonConvert.SerializeObject(Model));
};

Edit: This answer only applies to VS 2010. An upgrade in VS 2012 breaks this workaround as well.

How do I write unencoded Json to my View using Razor?

You do:

@Html.Raw(Json.Encode(Model.PotentialAttendees))

In releases earlier than Beta 2 you did it like:

@(new HtmlString(Json.Encode(Model.PotentialAttendees)))

Razor - Converting Json result from controller to a complex object

Your returning json, so using .load() makes no sense (you would typically use that when the method your calling returns a partial view).

Change your script to create the <optgroup> and <option> elements based on your data your method returns

var url = '@Url.Action("BindClasses", "Maps")';
var dropDownYear = $('#ddlYear');
dropDownYear.change(function() {
$.post(url, { yearId: $(this).val() }, function(data) {
$.each(data, function(index, item) {
var group = item.GroupName;
// use the above to build your <optgroup> element
$.each(item.Options, function(index, item) {
var value = item.Value;
var text = item.Text;
// use the above to build your <option> elements and append to the <optgroup> element
});
// append the <optgroup> to the <select id="classList"> element
});
});
});

Note the details of the code for generating the elements are in the answer to your previous question



Related Topics



Leave a reply



Submit