Description:-
In this example we explain that how to
create auto complete textbox in mvc4 using JQuery or how to create auto
complete textbox facility same like Ajax auto complete textbox in asp.net with
mvc. Here we provide facility same like as we normally used in asp.net with
Ajax. This is simple requirement that we have required in every web application
so here explain how to provide auto complete textbox facility to user in mvc
application. This functionality work same like as Ajax if user enter any
character in mvc country textbox then it's related country list are render in
below the textbox as a box list type same we have already seen in asp.net with
Ajax.
In mvc4 follow the below step Add a
model class with name Demo Model in model folder for the get and set detailed
information.
namespaceAutocomplete.Models { public class DemoModel { publicint id { get; set; } public string name { get; set; } public string mobile { get; set; } } }
Homecontroller.cs:-
public class HomeController : Controller { publicActionResult Index() { return View(); } //returns a list of suggestions [AcceptVerbs(HttpVerbs.Post)] public JsonResult Autocomplete(string term) { var result = new List<KEYVALUEPAIR>(); IList List = new List(); List.Add(new SelectListItem { Text = "test1", Value = "0" }); List.Add(new SelectListItem { Text = "test2", Value = "1" }); List.Add(new SelectListItem { Text = "test3", Value = "2" }); List.Add(new SelectListItem { Text = "test4", Value = "3" }); foreach (var item in List) { result.Add(new KeyValuePair(item.Value.ToString(), item.Text)); } var result3 = result.Where(s =>s.Value.ToLower().Contains(term.ToLower())).Select(w => w).ToList(); return Json(result3, JsonRequestBehavior.AllowGet); } //detail information of the selected term by id [AcceptVerbs(HttpVerbs.Post)] public JsonResult GetDetail(int id) { DemoModel model = new DemoModel(); //select data by id here display static data; if (id == 0) { model.id = 1; model.name = "Umesh Patel"; model.mobile = "9839485968"; } else { model.id = 2; model.name = "Chirag Patel"; model.mobile = "9384756383"; } return Json(model); }
Index.cshtml:-
@{ViewBag.Title = "Index"; }
Thanks for comments.....