jQuery UI is a jQuery plug-in which contains widgets and it is tightly integrate with jQuery API. To include jQuery UI across your MVC application refer the below scripts in layout view.
<script src="~/Scripts/jquery-1.8.2.min.js"></script> <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script> <script src="~/Scripts/jquery-ui-1.10.2.min.js"></script>
jQuery UI can be added to your MVC application using Nuget. This post outlines using jQuery Autocomplete in ASP.NET MVC project. jQuery UI relies on the theme and theme includes a style sheet and images. Every MVC project starts with the “base†theme under Content directory.
In order to use the Autocomplete in your application, refer the base them style sheet in layout view as shown below
Autocomplete behavior in this example lists the possible product names when user start typing inside the input element. You need to find the input element from JavaScript and attach the Jquery autocomplete behavior. You can use the data-autocomplete-source attribute to add the behavior
<script> $(document).ready(function () { $("input[data-autocomplete-source]").each(function () { var target = $(this); target.autocomplete({ source: target.attr("data-autocomplete-source") }); }); }); </script>
The input element looks as below
<input type="text" name="search" data-autocomplete-source="@Url.Action("SearchDemo", "Product")" />
Autocomplete expects a call to a data source and receive a collection of list object to show it to the user. You need to write action method in controller class as shown below
public ActionResult SearchDemo(string searchText) { var products = db.Products .Where(a => a.ProductName.Contains(searchText)).ToList(); return Json(products, JsonRequestBehavior.AllowGet); }
Autocomplete calls the datasource and passes the input value that you type in the control as a query string parameter named searchText. When the above code executes it then serializes the objects into JSON.