Monday, April 18, 2016

c# mvc autocomplete list

I had this challenge and I had to modify several solutions to get what I wanted. This is what worked for me:

Controller had this function:
[AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Create(string Prefix)
        {
            var agency = (from N in travel_agencies.ToList()
                          where N.travel_agent_name.ToLower().StartsWith(Prefix.ToLower()) || N.travel_agent_id.StartsWith(Prefix)
                          select new { N.travel_agent_name });
            return Json(agency, JsonRequestBehavior.AllowGet);
        }

the view had this:
$(document).ready(function () {
   $('#station_id').autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: "@Url.Action("Create", "ChargeBacks")",
                        type: "POST",
                        dataType: "json",
                        data: { Prefix: request.term },
                        success: function (data) {
                            response($.map(data, function (item) {
                                return { label: item.travel_agent_name, value: item.travel_agent_id };
                            }))
                        }
                    })
                },
                messages: {
                    noResults: "", results: ""

                }
            });
 });

the html element was:

<input type="text" name="station_id" id="station_id" class="form-control" />

No comments: