MVC Auto Complete
From Logic Wiki
Revision as of 09:26, 18 November 2016 by AliIybar (Talk | contribs) (Created page with "Category:Auto Complete Category:MVC Category:JQuery Category:Ajax === in a controller === <pre class="brush:csharp;"> [HttpPost] public Jso...")
in a controller
[HttpPost]
public JsonResult Index(string Prefix)
{
//Note : you can bind same list from database
List<City> ObjList = new List<City>()
{
new City {Id=1,Name="Latur" },
new City {Id=2,Name="Mumbai" },
new City {Id=3,Name="Pune" },
new City {Id=4,Name="Delhi" },
new City {Id=5,Name="Dehradun" },
new City {Id=6,Name="Noida" },
new City {Id=7,Name="New Delhi" }
};
//Searching records from list using LINQ query
var CityName = (from N in ObjList
where N.Name.StartsWith(Prefix)
select new { N.Name });
return Json(CityName, JsonRequestBehavior.AllowGet);
}
in razor
$(document).ready(function () {
$("#CityName").autocomplete({
source: function(request,response) {
$.ajax({
url: "/Home/Index",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Name, value: item.Name };
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
and also reference to these files
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>