18

I am using jQueryUI's autocomplete to allow the search of users. The documentation states that I am able to use an array for the source of the data in the following format: [ { label: "Choice1", value: "value1" }, ... ]

I have a base class that provides a list of unique Users which is inherited by my view-model. The view model has the following function:

public List<TestJson> GetUsers()
{
    return AvailableUsers
        .Select(u => new TestJson
            {
                Label = u.LastName + ", " + u.FirstName + "(" + u.UserId + ")",
                Value = u.UserId
            }).ToList();
}

public class TestJson
{
    public string Label { set; get; }
    public string Value { get; set; }
}

In my view, I use the above like so:

var userNameList = @Html.Raw(Json.Encode(Model.GetUsers()));

$("#UserName").autocomplete({
    source:userNameList 
});

Turns out userNameList is showing up like this:

[ { "Label": "Choice1", "Value": "value1" }, ... ]

instead of:

[ { label: "Choice1", value: "value1" }, ... ]

How can I get my array to show in the correct format?

EDIT: Based on input from comments, I have verified that both those formats are indeed functionally equivalent. I did a little more testing and it turns out that label and value are case sensitive. Changing my members to lower case seems to do the trick, but I don't feel that solution is the best. Any suggestions on how to change the string on the left side of the : (what is this called?) to lowercase?

Sumner Evans
  • 8,951
  • 5
  • 30
  • 47
Jeff
  • 2,283
  • 9
  • 32
  • 50
  • 6
    Either of those outputs should work fine. What's the issue you're having? – Jason P Sep 23 '13 at 18:37
  • 8
    `[ { label: "Choice1", value: "value1" }, ... ]` is functionally equivalent to `[ { "label": "Choice1", "value": "value1" }, ... ]`, or are you experiencing a problem? – Rob G Sep 23 '13 at 18:37
  • @RobG You are right! Please see my edit – Jeff Sep 23 '13 at 18:51
  • I was hit with the same. Just to get past this, I went with lower-cased properties. You might find an attribute decoration to control the name that's used during serialization but I don't see anything immediately available unless you're using the Newtonsoft library: http://stackoverflow.com/questions/8796618/how-can-i-change-property-names-when-serializing – Erik Noren Sep 23 '13 at 19:27
  • After a deeper look, it seems MVC uses JavaScriptSerializer which doesn't respect [DataMember] attributes like JSON.NET does. http://stackoverflow.com/questions/12497124/define-json-field-names-when-using-jsonresult so you can either switch to JSON.NET or look at this: http://stackoverflow.com/questions/1302946/asp-net-mvc-controlling-serialization-of-property-names-with-jsonresult – Erik Noren Sep 23 '13 at 19:31

6 Answers6

7
        //View.cshtml
<script type="text/javascript">
    var arrayOfArrays = JSON.parse('@Html.Raw(Json.Encode(Model.GetUsers()))');
</script>
Ahmed Elbendary
  • 379
  • 5
  • 7
  • JSON = JavaScript Object Notation so if it's a valid JavaScript object is there even a need to parse it? `var arrayOfArrays = @Html.Raw(Json.Encode(Model.GetUsers());` – keji Nov 13 '18 at 22:04
2

A simple Employee object:

public class Employee
{
public string Name { get; set; }
public string Age { get; set; }
public string ID { get; set; }   
}

Adding some instances of them to a List:

Employee oEmployee1 = 
new Employee{Name="Pini",ID="111", Age="30"};

Employee oEmployee2 = 
new Employee { Name = "Yaniv", ID = "Cohen", Age = "31" };
Employee oEmployee3 = 
new Employee { Name = "Yoni", ID = "Biton", Age = "20" };

List<Employee> oList = new List<Employee>() 
{ oEmployee1, oEmployee2, oEmployee3 };

Serializing then:

System.Web.Script.Serialization.JavaScriptSerializer oSerializer = 
new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(oList);

And here is the output:

[{"Name":"Pini","Age":"30","ID":"111"},
{"Name":"Yaniv","Age":"31","ID":"Cohen"},
{"Name":"Yoni","Age":"20","ID":"Biton"}]

Also below link has similar example

Convert Object to JSON in MVC 4

Community
  • 1
  • 1
Soner Sevinc
  • 400
  • 4
  • 19
2

Comments by Jason P and Rob G are correct. The two formats in questions are equivalent. Turns out my issue was with the casing. DOH!

I just changed the properties in my class to be lower case. Thought, I would love to see an alternate solution. I will choose this one until a better one is submitted.

Jeff
  • 2,283
  • 9
  • 32
  • 50
  • 2
    Came here to figure out how to convert a C# list of objects to a javascript array of objects -- your problem was my solution. Thanks. – Cody Mar 27 '14 at 20:31
1

If you passing List of object though MVC model and want to store it an array variable in script section on .cshtml page PFB code snipt :-

@Html.Raw(Json.Encode(Model.ListPropertyName))
satya prakash
  • 87
  • 1
  • 5
1

As of .NET Core 3.0, it's simpler.

Instead of doing this in your view:

var userNameList = @Html.Raw(Json.Encode(Model.GetUsers()));

Do this:

var userNameList = @Json.Serialize(Model.GetUsers());

Note that:

  1. Converting keys to camelCase is the default behavior.
  2. The result type is IHtmlContent, which does not need to be wrapped inside @Html.Raw().
MarredCheese
  • 17,541
  • 8
  • 92
  • 91
0

I assume you are using MVC. WebAPI will default to camelCase while MVC defaults to PascalCase.

See also: Proper JSON serialization in MVC 4 and http://www.matskarlsson.se/blog/serialize-net-objects-as-camelcase-json.

Community
  • 1
  • 1
Colin Young
  • 3,018
  • 1
  • 22
  • 46