Almost in each modern website project one of the feature is suggesting user possible items to select when he start typing one of them. Such functionality is done by using control named autocomplete. Under the hood it consists of at least three elements:
- UI control which allow user to type some text - mainly this in HTML input of text type
- Server-side function which serves data to be auto-completed
- Client-side logic (written in JavaScript) which , by using AJAX, send request to the server asynchronously and then process the results.
When we think about creating autocomplete control in ASP.NET MVC 4 we definitely should take a look at jQueryUI framework. One of the feature of this framework is autocomplete control which enables users to quickly find and select from a pre-populated list of values as they type, leveraging searching and filtering. That sounds very good and is excellently what we are looking for.
First step in autocomplete control creation is creating a new MVC 4 project in Visual Studio 2012 (picture 1.) and set it as Internet Application with Razor engine. After whole project created successfully , press F5 and validate build result - should complete without any error.
Picture 1. Creating MVC 4 project. |
Default ASP.MVC 4 project template already contains several very important features.One of them, which will be very usefull in our case, is predefined set of the JavaScript files (including jQuery and jQueryUI) located in the ~/Scripts folder. Other stuff is connected with membership provider and won`t be used in this tutorial, but to make it easier lets stay with template structure without removing anything.
First think we need to add to our solution in our custom model which will store information for view. The assumption here is we want to create two auto-completes that will be part of new AdminController. First one will be responsible for auto-completing car brand and the second will help with choosing proper globalization. Based on this information we can create our first class model which will be located in ~/Models/Admin/ManageModel.cs .Our model will store ifnroation about SelectedCarBrandId and culture Id - very simple.
Code Snippet
- namespace Autocomplete.Models.Admin
- {
- /// <summary>
- /// Stores information for manage view.
- /// </summary>
- public class ManageModel
- {
- /// <summary>
- /// Gets or sets the selected car brand id.
- /// </summary>
- public int? SelectedCarBrandId { get; set; }
- /// <summary>
- /// Gets or sets the selected culture code.
- /// </summary>
- public string SelectedCultureCode { get; set; }
- }
- }
Tip:
For C# beginners worth to explain is type of the SelectedCarBrandId - this is int?. Integer is value type so this mean that has default value assigned after declaration (0 at this case). To allow put null value to object of integer type we need to declare our type as Nullable<T> struct and this is equals with the int? syntax. Thanks doing that we can type int? integerValue = null;
After we done with model, now it`s time for creating new controller (in ~/Controller/AdminController.cs). Creating new controller cause that we have new route value available (http://localhost/Admin/) in our project but there is no view to present. But focus at the controller first. Our AdminController containts two function and both of them returns ActionResults (read - returns view). Name of this function is also the same (so we can expect new action available on website http://localhost/Admin/Manage) but whole signature is different. First of all second fuction takes model as parameter and additionally is decorated with HttpPostAttribute . The reason why it is done in that way is difference between how to get this two action. When user open page under the hood uses GET request without any parameters (in this case). Then he changing something on the website and click the submit button - it causes POST request and sends HTML form to the server. That is why we have two function where first (GET) function just render the view and the second (POST) process provider by user data (this data is binded to the model of the ManageModel type at this case).
Code Snippet
- namespace Autocomplete.Controllers
- {
- using System.Collections.Generic;
- using System.Globalization;
- using System.Linq;
- using System.Web.Mvc;
- using Autocomplete.Models.Admin;
- /// <summary>
- /// Controlles for admini purposes.
- /// </summary>
- public class AdminController : Controller
- {
- /// <summary>
- /// Generate view for main admin page.
- /// </summary>
- /// <returns>View of the main page.</returns>
- public ActionResult Manage()
- {
- ManageModel model = new ManageModel();
- return View(model);
- }
- [HttpPost]
- public ActionResult Manage(ManageModel model)
- {
- return View();
- }
- }
- }
Next step is create a simple view to display UI for the user. Our view, called Manage.cshtml (picture 2.) will be stored in the following location ~/Views/Admin/Manage.cshtml and will take main layout from parent page which in this case will be _Layout.cshtml.
Picture 2. Adding view with default layout. |
Code Snippet
- @using Autocomplete.Helpers;
- @model Autocomplete.Models.Admin.ManageModel
- @{
- ViewBag.Title = "Manage";
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
- @using (Html.BeginForm("Manage", "Admin"))
- {
- <h2>
- Manage</h2>
- <input type="submit" value="Submit" />
- }
Now it`s time for achieve our goal and introduce auto-completes controls. Before we do that we need make sure that we provided model for our view already (we want to use ManageModel for Manage view) which allow us to work with a strongly typed view later. Making such connection is quite easy and its noting else then putting namespace declaration for model and calling model type with a @model directive (line 1 and 2 above). Next we switch to implementation of our helper method which will extend standard HtmlHelper by adding new extension function with partial signature MvcHtmlString AutocompleteFor<TModel, TValue>. The most important thing in the function signature is that it takes model type (TModel) and by expression also takes model properties as TValue. Method has two overloaded definition (simple and more advance) but in both cases the most important thing is actionUrl parameters which defines controller action which will be called when user types more then two characters into auto-complete (will be introduced later).
Code Snippet
- namespace Autocomplete.Helpers
- {
- using System.Linq.Expressions;
- using System.Text;
- using System.Web.Mvc;
- using System.Web.Mvc.Html;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- public static class AutocompleteHelper
- {
- /// <summary>
- /// Create autocomplete control by using jQueryUi.
- /// </summary>
- /// <typeparam name="TModel">Type of the view model.</typeparam>
- /// <typeparam name="TValue">Selected properties type.</typeparam>
- /// <param name="helper">Html helper to extend.</param>
- /// <param name="expression">The HTML helper instance that this method extends.</param>
- /// <param name="actionUrl">Controller action to call after user start typing.</param>
- /// <returns>Autocomplete HTML string.</returns>
- public static MvcHtmlString AutocompleteFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string actionUrl)
- {
- return CreateAutocomplete(helper, expression, actionUrl, null, null);
- }
- /// <summary>
- /// Create autocomplete control by using jQueryUi with additional parameters.
- /// </summary>
- /// <typeparam name="TModel">Type of the view model.</typeparam>
- /// <typeparam name="TValue">Selected properties type.</typeparam>
- /// <param name="helper">Html helper to extend.</param>
- /// <param name="expression">The HTML helper instance that this method extends.</param>
- /// <param name="actionUrl">Controller action to call after user start typing.</param>
- /// <param name="isRequired">Determines field is required.</param>
- /// <param name="placeholder">Placeholder text to present when control containts no data.</param>
- /// <returns>Autocomplete HTML string.</returns>
- public static MvcHtmlString AutocompleteFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string actionUrl, bool? isRequired, string placeholder)
- {
- return CreateAutocomplete(helper, expression, actionUrl, placeholder, isRequired);
- }
- }
- }
In the implementation above both function calls the same method in the function body. That function is responsible for creating HTML tags for auto-complete control based of passed parameters. There is several important places inside this function that is worth to discuss:
- line 49: contains adding attribute for the input control that will be kind of representative for auto-complete control in whole solution.
- line 50: URL action to be called after user typed more then two characters in control.
- line 66: creating <input type='hidden' /> for storing value (not label) selected by user from auto-complete. Name of the value is equal to the property name indicated in expression (field of the model). This also set default value based on model value.
- line 68: add to the auto-complete attribute which will store name of the associated hidden control.
- line 71: creating input with set of attributes that will be used by JavaScript to detect and generate auto-complete during run-time.
Code Snippet
- private static MvcHtmlString CreateAutocomplete<TModel, TValue>(HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string actionUrl, string placeholder, bool? isRequired)
- {
- var attributes = new Dictionary<string, object>
- {
- { "data-autocomplete", true },
- { "data-action", actionUrl }
- };
- if (string.IsNullOrWhiteSpace(placeholder))
- {
- attributes.Add("placeholder", placeholder);
- }
- if (isRequired.HasValue && isRequired.Value)
- {
- attributes.Add("required", "required");
- }
- Func<TModel, TValue> method = expression.Compile();
- var value = method((TModel)helper.ViewData.Model);
- var baseProperty=((MemberExpression) expression.Body).Member.Name;
- var hidden = helper.Hidden(baseProperty, value);
- attributes.Add("data-value-name", baseProperty);
- var automcompleteName = baseProperty + "_autocomplete";
- var textBox = helper.TextBox(automcompleteName, null, string.Empty, attributes);
- var builder = new StringBuilder();
- builder.AppendLine(hidden.ToHtmlString());
- builder.AppendLine(textBox.ToHtmlString());
- return new MvcHtmlString(builder.ToString());
- }
Lets now focus on the auto-complete logic. Because some action of an auto-complete takes place on the client-side we need to use JavaScript code to create such behavior and also to send AJAX request and process data from a response. First of all lets then create new file AutocompleteScript.js located in the path ~/Script/AutocompleteScript.js (code below). After website is fully loaded we call CreateAutocomplete function (line 1-3). This function under the hood by using jQuery attribute selector gathers all elements with a data-autocomplete attribute (and our auto-complete will have such one). Later it iterates through selected collection by using each function and process each element separately. During processing is takes URL action form which point to controller function (line 7) in the next line call auto-complete creation. Inside that creation, except success function that will be called after user select item from suggestion list, we have source which is simple AJAX call with parameters:
- url: action on the controller.
- dataType: set as jSon.
- data: provided by the user text inside the control which will be used to filter the result set.
- success: process the response and fill suggestion list
Code Snippet
- $(document).ready(function () {
- CreateAutocomplete();
- });
- function CreateAutocomplete() {
- var inputsToProcess = $('[data-autocomplete]').each(function (index, element) {
- var requestUrl = $(element).attr('data-action');
- $(element).autocomplete({
- minLength: 2,
- source: function (request, response) {
- $.ajax({
- url: requestUrl,
- dataType: "json",
- data: { query: request.term },
- success: function (data) {
- response($.map(data, function (item) {
- return {
- label: item.Label,
- value: item.Label,
- realValue: item.Value
- };
- }));
- },
- });
- },
- select: function (event, ui) {
- var hiddenFieldName = $(this).attr('data-value-name');
- $('#'+hiddenFieldName).val(ui.item.realValue);
- }
- });
- });
- }
We almost done and our solution is almost ready. We heed to complete just several step more:
1) We put client-side auto-complete login in separated JavaScript file that is why we need to attach it to our view. To do that first of all it need to become part of the ScriptBundle object - so the code presented below need to be added to the ~/App_Start/BundleConfig.cs file. Thanks doing that on our Manage view we can then put line @Scripts.Render("~/bundles/jquery").
Code Snippet
- bundles.Add(new ScriptBundle("~/bundles/custom").Include(
- "~/Scripts/AutocompleteScript.js"));
2) Create two AdminController methods that will provide data for auto-completes. Remember here that parameter name have to be equals 'query' and jSon result must AllowGet.
Code Snippet
- /// <summary>
- /// Autocompletes car brand
- /// </summary>
- /// <param name="query">Search term.</param>
- /// <returns>Json with search result.</returns>
- [HttpGet]
- public JsonResult AutocompleteCars(string query)
- {
- var data = new Dictionary<int, string>
- {
- { 1, "Audi" },
- { 2, "BMW" },
- { 3, "Opel" },
- { 4, "Citroen" },
- { 5, "Toyota" }
- };
- query = query.ToLower();
- var result = data.Where(c => c.Value.ToLower().StartsWith(query)).Select(c => new { Value = c.Key, Label = c.Value });
- return this.Json(result, JsonRequestBehavior.AllowGet);
- }
- /// <summary>
- /// Autocomplete culture by term.
- /// </summary>
- /// <param name="query">Term to search.</param>
- /// <returns>Json with cultures.</returns>
- [HttpGet]
- public JsonResult AutocompleteCulture(string query)
- {
- query = query.ToLower().Trim();
- var result = CultureInfo.GetCultures(CultureTypes.SpecificCultures)
- .Where(c => c.DisplayName.ToLower().StartsWith(query))
- .Select(c => new { Value = c.LCID, Label = c.DisplayName });
- return this.Json(result, JsonRequestBehavior.AllowGet);
- }
3) Add our auto-complete extension function to the view and provide required parameters:
- Model property indicated by the expression
- Controller function generated by Action.
Code Snippet
- @Styles.Render("~/Content/themes/base/css")
- @using (Html.BeginForm("Manage", "Admin"))
- {
- <h2>
- Manage</h2>
- <span>Car brand:</span> @Html.AutocompleteFor(c => c.SelectedCarId, Url.Action("AutocompleteCars", "Admin"))
- <br />
- <span>Globalization name:</span>@Html.AutocompleteFor(c => c.SelectedCultureCode, Url.Action("AutocompleteCulture", "Admin"), true, "Start typing culture name....")
- <br />
- <input type="submit" value="Submit" />
- }
4) Run the solution and go to the http://localhost:port/Admin/Manage and feel free to test.
Source code is available here.
Enjoy