Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 558
user1527762 Avatar asked Mar 15 '23 23:03

user1527762


1 Answers

Put your JSON between single quote NOT double quote characters:

<div id = "test" test-att = '@Html.Raw(Json.Encode(Model.list))' /> 
like image 54
Sam FarajpourGhamari Avatar answered Apr 08 '23 02:04

Sam FarajpourGhamari