2

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Hi, the first one does work, thanks! But I'm learning, wanted to know why do we have to do JSON.parse as we are already doing Json.Encode? And why Json.Encode encodes the array in quotes?
Amended my answer with an explanation of why you need to parse the response! :) If my answer helped, please select it as the right answer, it helps me out.
Great! marked it as right answer. One small thing I noticed, my list has values with commas, Example "Doe, John" and the Json.Encode seems to be not working well with that. For the above element in the list I get the output from Json.Encode as array ["Doe, which is incorrect. Any ideas on how to escape the commas for the elements in the list?
EDIT: actually it's not the comma but space that is throwing it off. "Doe,John" works fine but "Doe, John" does not.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.