RPM1984
RPM1984

Reputation: 73112

ASP.NET MVC 3 Serializing to JSON

I've got an ICollection<T> of POCO like this:

public class SearchJsonModel
{
   public string label { get; set; }
   public string category { get; }
}

In my Razor view, i serialize it as follows:

<script type="text/javascript">
   var jsonArray = @Html.Raw(Json.Encode(Model));
</script>

But the output is this:

var jsonArray = [
   {"category":"Names","label":"Joe"},
   {"category":"Names","label":"John"}
];

Which is causing problems because of the quotes around the properties.

I need to access the properties of each JSON object, so I would expect it to be like this:

var jsonArray = [
   {category:"Names",label:"Joe"},
   {category:"Names",label:"John"}
];

That way i can do something like this:

$.each(jsonArray, function(index, item) {
   var x = item.category;
});

What am i doing wrong? Am i using the wrong method to encode?

Upvotes: -1

Views: 1897

Answers (2)

Shyju
Shyju

Reputation: 218732

This JSON is valid (checked in JSONLINT). The quotes should be there.

You can get the category values like this without any problem

$(function(){
   var data=[
   {"category":"Names","label":"Joe"},
   {"category":"Names","label":"John"}
];

    $.each(data,function(index,item){
          alert(item.category);
    });        

});​

Sample http://jsfiddle.net/DKnBh/

Upvotes: 2

Garrett Vlieger
Garrett Vlieger

Reputation: 9494

This is standard JSON and shouldn't cause a problem.

See here for more info: in JSON, Why is each name quoted?.

Upvotes: 0

Related Questions