ASP.NET MVC converts a list of models from a string with spaces into a javascript array

I am using ASP.NET MVC (with Razor) and jQuery

I have a list of strings in my controller, and I pass a partial view to the model with the list below.

List<string> list = new List<string>();
list.Add("Texas");
list.Add("New York");

On the client in my side of the cshtml file I have:

<div id = "test", test-att = @Html.Raw(Json.Encode(Model.list)) />

In my javascript file, I:

var javascriptArray = JSON.parse($('#test').attr('test-att'));

I get an error "unexpected end of input".

Using the Chrome dev tool console, I see the following:

$('#test') : <div id ="test" test-att = "["Texas", "New" York"]>

$('#test').attr('test-att') : "["Texas","New"

I expect: "["Texas","New York"]"

It looks like it got messed up due to space before passing it to JSON.parse. He seems to stop when he finds a place.

Any ideas on how to fix this?

+4
source share
4

JSON NOT :

<div id = "test" test-att = '@Html.Raw(Json.Encode(Model.list))' /> 
+7

cshtml

<div id = "test" test-att = "@Html.Raw(Json.Encode(Model.list))" />
0

, 2 , :

  • Json "( ), . , XML .

2 , , , " Json Encoded"

<div id = "test", test-att ="@Html.Raw(Json.Encode(Model.list).Replace("\"","&quot;")" />

0

, @Html.Raw. -

<div id='dd' data-att="@Json.Encode(list)">

javascript .

var a = document.getElementById('dd');
JSON.parse(a.dataset.att);

. @Html.Raw, . @Html.Raw -

<div id='dd' data-att="@Json.Encode(list.Select(x=> Html.Raw(x).ToHtmlString()).ToList<string>())">

This will work with a double quote.

0
source

All Articles