简体   繁体   中英

How parse json array of object inside autcomplete c# mvc

I have an auto complete method.

$("#txtSearch").autocomplete({

                  source: function (request, response) {
                      $.ajax({
                          url: "/Home/Getsrchresult",
                          type: "POST",
                          dataType: "json",
                          data: { term: request.term, location: $('#location').val() },
                          success: function (data) {
                              response($.map(data, function (item) {
                                  return {


                                   label: item.srchresult, value: item.srchresult
                                    };
                              }))

                          }
                      })
                  }
              });

my controller passes multidimension array.How to place all data inside autocmplete textbox

controller

                var fd2 = (from r in db.Restaurants
                       where r.restname.ToLower().Contains(term.ToLower())
                       orderby r.state == location descending
                       select new { searchresult = r.restname ,place=r.place


                       }).Take(10);
  return Json(fd2, JsonRequestBehavior.AllowGet);

Response is like this

[{"srchresult":"foodtakeaway","place":"karnataka"},{"srchresult":"ssdf","place":"dfsaf"}]

This should work

$("#txtSearch").autocomplete({
     source: function (request, response) {                  
               $.ajax({
                    url: "/Home/Getsrchresult",
                    type: "POST",
                    dataType: "json",      
                    data: { term: request.term,location:$('#location').val() },
                    success: function (data) {
                        response($.map(data, function (item) {                   
                            return { label: item.place, value: item.place };
                        }))
                    }
                })
            }  
});

Assuming you are returning JSON like this

[
    {
        "srchresult": "foodtakeaway",
        "place": "karnataka"
    },
    {
        "srchresult": "ssdf",
        "place": "dfsaf"
    }
]

I have used item.place for label and value property, you may replace it with item.srchresult as needed.

Suggestion : Use MVC Helper methods( Url.Action ) to generate the url to your action methods, instead of hardcoding

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM