parse model data to JSON object

Viewed 609

I need to convert a list of model objects into a JSON list.

<a data-model="@Model.Schools"></a>");

The list of schools is parsed to a jquery eventhandler when the above button is pressed (I left some code out here)

Here, I naturally want to read the list of schools to a json list.

var items = JSON.stringify(button.data('model'))
var items2 = JSON.parse('"' + button.data('model') + '"')

I tried the above, however without any luck, it still yells at me for trying to convert a System.Collections.Generic.List`1.

Also I tried to serialize the object to JSON at the button, i.e. @HTML.raw(Json.Serialize(Model.Schools) but it just gives me an empty object in my jQuery...

Therefore, how do I convert a Model object to a json object in jQuery?

1 Answers

If I get your problem statement correctly, it seems you are pretty much there.

you need to serialise your list into Razor attribute (don't use @Html.Raw helper as it will not escape your string and mess with your page):

Full .net framework

<a id="btnModel" data-model="@Json.Encode(Model.Schools)" onclick="process()">TEST</a>
<!-- assuming you have Newtonsoft.Json package installed, the following line should also work-->
<a id="btnModel" data-model="@Newtonsoft.Json.JsonConvert.SerializeObject(Model.Schools)" onclick="process()">TEST</a>

and then in your Javascript:

function process() {
    var m = $('#btnModel').data('model');               
    alert(JSON.stringify(m));
}

check out this dotnet fiddle for working example

.net core 3

Apparently the built-in serilizer somehow garbles the formatting so it needs proper html encoding. This unfortunately will mean you have to decode it in Javascript. One way to avoid this hassle would be to output your json string into javasctipt block (see second example)

<a id="btnModel" data-model="@Html.Encode(Json.Serialize(Model.Schools))" onclick="process()">Method 1 - Lotsa pain</a>
<a id="btnModel1" onclick="process1()">Method 2 - Less back and forth</a>
function decodeHtml(html) {
    var txt = document.createElement("textarea");
    txt.innerHTML = html;
    return txt.value;
}
function process() {
    var a = $('#btnModel').data('model');
    a = JSON.parse(decodeHtml(a));
    alert(JSON.stringify(a));
}
function process1() {
    var a = @Json.Serialize(Model.Schools);
    alert(JSON.stringify(a));
}

Related