user1527762
user1527762

Reputation: 957

ASP.NET MVC converting a model list of string with spaces into a javascript array

I'm using ASP.NET MVC (with Razor) and JQuery

I have a list of strings in my controller and I render the partial view passing in the model with the below list.

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

On client in my cshtml file side I have:

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

In my javascript file I do:

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

I get an error "unexpected end of input".

Using Chrome dev tools console I see the following:

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

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

I'm expecting : "["Texas","New York"]"

Looking like its getting messed up because of the space before being passed in JSON.parse. It seems to stop when it finds a space.

Any ideas on how to fix this?

Upvotes: 4

Views: 2786

Answers (4)

th1rdey3
th1rdey3

Reputation: 4358

It seems to me the culprit is @Html.Raw. If you use the following -

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

Then parsing with javascript doesn't fail.

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

Single quote or double quote doesn't matter. But if you use @Html.Raw then double quote gives you the said error. You can use @Html.Raw against each item of your list instead -

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

This will work with double quote.

Upvotes: 0

Poppuff Arthem
Poppuff Arthem

Reputation: 19

There seems to be 2 issues with what you have :

  1. The Json encoder uses " (double quotes) to delimitate strings. It's not gonna work since in XML double quote are used to delimitate attributes.

For this issue you have 2 solutions the easiest one would probably be replacing every " in the Json Encoded string by

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

Upvotes: 0

user2315314
user2315314

Reputation: 1

Content of cshtml file will be like as bellow

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

Upvotes: 0

Sam FarajpourGhamari
Sam FarajpourGhamari

Reputation: 14741

Put your JSON between single quote NOT double quote characters:

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

Upvotes: 7

Related Questions