Reputation: 93
I'm trying to pass data from cshtml file to my Javascript via data-* attribute. I'm using method like this
@using Newtonsoft.Json;
@{ var list = JsonConvert.SerializeObject(Model.ListToPass); }
<div id="mainView"
[email protected](list)>
</div>
which works okay in theory, but since some of my data, has values containing space, eg. "Name Something", my data is actually passed as
<div id="mainView"
data-custom="[{"Id":1,"Field":"Name">
</div>
What is the way to do this correctly?
Upvotes: 0
Views: 1222
Reputation: 4903
Answer as per comment validated by @MeeraWeeks:
Solution:
Adding '
apostrophe to @Html.Raw(list)
that ignore the space in the generated html
.
The div
tag will be:
@using Newtonsoft.Json;
@{ var list = JsonConvert.SerializeObject(Model.ListToPass); }
<div id="mainView"
data-custom='@Html.Raw(HttpUtility.HtmlEncode(list))'>
</div>
Upvotes: 1