Search code examples
c#jqueryasp.net-mvcjquery-ui

Convert C# List of object to JavaScript array of objects


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?


Solution

  • 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.