user1527762
user1527762

Reputation: 957

ASP.NET MVC Help trying to convert a list to 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("test1");
list.Add("test2");

On client side I have:

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

In my javascript file I do:

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

I'm expecting a result ["test1", "test2"] but I'm seeing "["test1", "test2"]"

Any ideas on how to fix this?

Upvotes: 2

Views: 1994

Answers (2)

James Pederson
James Pederson

Reputation: 404

Quick fix to the javascript for this:

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

The reason for this is because the JSON you have is in a string (hence the quotes). Using the JSON.parse() method, it converts it into an object in javascript that can be used as you expect.

Upvotes: 3

Andrei
Andrei

Reputation: 44600

I usually do something like this in Javascript:

var data = function() { return @Html.Raw(Json.Encode(Model)); }();

Or:

function set(value){
    return value;
}

var data = set(@Json.Encode(Model));

If you simply do:

var data = @Json.Encode(Model);

it will still work but VS will be thinking that there is a syntax error, so I'd rather use one of 1st two options.

Upvotes: 0

Related Questions