kolbe
kolbe

Reputation: 27

how to change json format in asp.net mvc?

I'm trying to make autocomplete textbox using this link

https://github.com/devbridge/jQuery-Autocomplete

but I got this error Uncaught TypeError: Cannot read property 'length' of undefined

this is my action method

public JsonResult GetNews(string prefix)
{
  var newsList = NewsDataRoot.AutoCompleteTitle(prefix).Select(n => new
  {
    value = n.Title,
    data = n.Id
  }).ToList();
  var myjson = Json(newsList, JsonRequestBehavior.AllowGet);
  return myjson;
}

and it return this result when I test it in browser

[{"value":"this is a test","data":2006}]

I found the format must be

{
    suggestions: [{
        "value": "United Arab Emirates",
        "data": "AE"
    }, {
        "value": "United Kingdom",
        "data": "UK"
    }, {
        "value": "United States",
        "data": "US"
    }, {
        "value": "United Funes",
        "data": "DAN"
    }]
}

how can do this? thanks a lot!

also as you can see I tried transformResult but it doesnt worked

<script>

    $('#autocomplete').autocomplete({
        serviceUrl: '/TestAutoComplete/GetNews',
        paramName: 'prefix',
        transformResult: function(response) {
            return {
                suggestions: $.map(response.myData, function(dataItem) {
                    return { value: dataItem.valueField, data: dataItem.dataField };
                })
            };
        },
        onSelect: function (suggestion) {
            alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
        }
    });

</script>

Upvotes: 1

Views: 413

Answers (2)

mshouman
mshouman

Reputation: 384

if you want to set number to be numeric string you can try convert its value to string

        public JsonResult GetNews(string prefix)
        {
            var newsList = NewsDataRoot.AutoCompleteTitle(prefix).Select(n => new
            {
                value = n.Title,
                data = n.Id.ToString()

            }).ToList();

            var myjson = Json(new {suggestions = newsList}, JsonRequestBehavior.AllowGet);
            return myjson;
        }

Upvotes: 0

Kevin Smith
Kevin Smith

Reputation: 14476

Try this, creates an anonymous object which just has the suggestions property

var newsList = NewsDataRoot.AutoCompleteTitle(prefix)
       .Select(n => new {
             value = n.Title,
             data = n.Id
       }).ToList();

var myjson = Json(new { suggestions = newsList }, JsonRequestBehavior.AllowGet);

Upvotes: 1

Related Questions