user3300195
user3300195

Reputation: 69

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"}]

Upvotes: 0

Views: 403

Answers (1)

Shyju
Shyju

Reputation: 218722

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

Upvotes: 1

Related Questions