0

In razor, this is what I have:

<span data="@(new { prop1 = "prop1val", prop2 = 5 })" id="span1"></span>

And, in JS, I want to parse that data attr val into a JSON object.

var dataObj = JSON.parse($("#span1").attr("data"));
alert(dataObj.prop1); // should alert "prop1val"

The way the razor is rendering is like this:

<span data="{ prop1 = prop1val, prop2 = 5 }" id="span1"></span>

Do I need to do something like @(new {...}).toJsonString() ? Is there something within razor I can just use?

Thanks!

1 Answer 1

1

You need to serialize the string to JSON format.

You can write @(new JavaScriptSerializer().Serialize(new { ... }))

If you want to, you can create an extension method to do that as an HTML helper:

public static string ToJson(this HtmlHelper html, object obj) {
    return new JavaScriptSerializer().Serialize(obj);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.