1

I have a feeling there is a simple answer to this, but I am having a problem when returning my JSON data to the JQuery UI Autocomplete function. I am using the 'label' and 'value' fields so I can store an id field. The problem is I am unable to parse the values in the object once they are passed back to the JQuery function.

in ASP.NET C#, I have an object:

public class AutoCompleteItem
{
    public string label { get; set; }
    public string value { get; set; }
}

and setting them into a list, formatting as JSON and then returning:

List<AutoCompleteItem> autoCompleteItems = new List<AutoCompleteItem>();
// Loop through data, add objects to list
var oSerializer = new JavaScriptSerializer();
string sJSON = oSerializer.Serialize(autoCompleteItems);
return sJSON;

JSON data after being passed to JQuery:

"[{"label":"Steve","value":"ID4545"},{"label":"Joe","value":"ID1212"},{"label":"Rick","value":"ID6767"}]"

and this is the function i am using to try and get the data from the JSON:

success: function (data) {
      response($.map(data.d, function (item) {
          return {
              label: item.label,
              value: item.value
          }
                                }));
},

I noticed that before I used the 'label', 'value' format, I had it working with just an IList string. The data passed did not have quotes on the outside, whereas my original example does

["Steve", "Joe", "Rick"]

I don't know if this is related to the problem or not, but I have tried a number of things to no avail. Any help is appreciated!

8
  • 3
    see the data.d is correct. You need convert data in jquery response? Commented Apr 12, 2012 at 19:08
  • Why are you trying to map data.d to an array containing objects with the exact same structure? Shouldn't using data.d directly be the same? (or do you want to preserve the original response intact?). Besides, you are using data.d, but I don't see any "d" property on the JSON data you showed before. Maybe if you use data directly? Commented Apr 12, 2012 at 19:10
  • i believe 'd' is something unique to .NET, it houses my object in question. Commented Apr 12, 2012 at 19:11
  • @Jones - yes, I am trying to get the labels to display in the auto suggest box, and store the values with each entry for when they are selected. Commented Apr 12, 2012 at 19:12
  • 1
    if you use the converter, then use json2.js you can do alert(JSON.stringify(data)); as the first line in your success: to see exactly what you have returned. Commented Apr 12, 2012 at 19:52

3 Answers 3

2

There's no .d property in the JSON you have shown. So:

success: function (data) {
    response(
        $.map(data, function (item) {
            return {
                label: item.label,
                value: item.value
            };
        })
    );
},

But if you use an ASP.NET Page method then you have the .d property and you don't need to manually serialize the JSON. For example, you could have the following PageMethod in your code behind:

[WebMethod]
public static List<AutoCompleteItem> GetAutoCompleteValues(string term)
{
    // the term variable will contain what the user entered so far

    var autoCompleteItems = new List<AutoCompleteItem>();
    // Loop through data, add objects to list
    return autoCompleteItems;
}

and then:

source: function(request, response) {
    $.ajax({
        url: '/foo.aspx/GetAutoCompleteValues',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ term: request.term }),
        success: function(data) {
            response(
                $.map(data.d, function(item) {
                    return {
                        label: item.label,
                        value: item.value
                    };
                });
            );
        })
    });
});
Sign up to request clarification or add additional context in comments.

3 Comments

ASP.NET serializes JSON responses in a d property. What he has is correct.
@villecoder, yes, but he is not using ASP.NET to serialize. He does this manually. See the JavaScriptSerializer class he is using? See the JSON he has shown in the question. No trace of any .d whatsoever. Now look at the page method I have shown in my answer. This will use the .d property.
It's true that he's pumping this through a JavaScriptSerializer. But all that does is change the d property from a JSON object to a String. ASP.NET still responds to the AJAX request with a JSON object that uses the d property for the data.
0

You shouldn't need to convert the JSON response - jQuery UI is already expecting those tokens.

From jQuery UI documentation:

$(function() {
        function log( message ) {
            $( "<div/>" ).text( message ).prependTo( "#log" );
            $( "#log" ).scrollTop( 0 );
        }

        $( "#birds" ).autocomplete({
            source: "search.php",
            minLength: 2,
            select: function( event, ui ) {
                log( ui.item ?
                    "Selected: " + ui.item.value + " aka " + ui.item.id :
                    "Nothing selected, input was " + this.value );
            }
        });
    });

You have direct access to the value and id properties of the item(s) as the second parameter jQuery passes to those event handlers (in the documentation example select:). No conversion should be required.

Comments

0

Why use JavaScriptSerializer() in the first place? You only need

 public ActionResult GetUserAutoComplete(string term)
 {  
      var users = _userRepository.GetUsersByTerm(term);
      var autoCompleteData = users.Select(x => new { label = x.Name + " " + x.Surname, value = x.Name + " " + x.Surname, id = x.UserId, }).ToArray();
      return Json(data, JsonRequestBehavior.AllowGet);
}

1 Comment

He's not using ASP.NET MVC (or at the very least, he hasn't mentioned it).

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.