ASP.Net MVC 2 Auto Complete Textbox With Custom View Model Attribute & EditorTemplate

Posted by SeanMcAlinden on ASP.net Weblogs See other posts from ASP.net Weblogs or by SeanMcAlinden
Published on Fri, 11 Jun 2010 23:03:00 GMT Indexed on 2010/06/11 23:13 UTC
Read the original article Hit count: 2664

In this post I’m going to show how to create a generic, ajax driven Auto Complete text box using the new MVC 2 Templates and the jQuery UI library.

The template will be automatically displayed when a property is decorated with a custom attribute within the view model.

The AutoComplete text box in action will look like the following:

AutoComplete 

The first thing to do is to do is visit my previous blog post to put the custom model metadata provider in place, this is necessary when using custom attributes on the view model.

http://weblogs.asp.net/seanmcalinden/archive/2010/06/11/custom-asp-net-mvc-2-modelmetadataprovider-for-using-custom-view-model-attributes.aspx

Once this is in place, make sure you visit the jQuery UI and download the latest stable release – in this example I’m using version 1.8.2. You can download it here.

Add the jQuery scripts and css theme to your project and add references to them in your master page.

Should look something like the following:

Site.Master
  1. <head runat="server">
  2.     <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
  3.     <link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
  4.     <link href="../../css/ui-lightness/jquery-ui-1.8.2.custom.css" rel="stylesheet" type="text/css" />
  5.     <script src="../../Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
  6.     <script src="../../Scripts/jquery-ui-1.8.2.custom.min.js" type="text/javascript"></script>
  7. </head>

Once this is place we can get started.

Creating the AutoComplete Custom Attribute

The auto complete attribute will derive from the abstract MetadataAttribute created in my previous post.

It will look like the following:

AutoCompleteAttribute
  1. using System.Collections.Generic;
  2. using System.Web.Mvc;
  3. using System.Web.Routing;
  4. namespace Mvc2Templates.Attributes
  5. {
  6.     public class AutoCompleteAttribute : MetadataAttribute
  7.     {
  8.         public RouteValueDictionary RouteValueDictionary;
  9.         public AutoCompleteAttribute(string controller, string action, string parameterName)
  10.         {
  11.             this.RouteValueDictionary = new RouteValueDictionary();
  12.             this.RouteValueDictionary.Add("Controller", controller);
  13.             this.RouteValueDictionary.Add("Action", action);
  14.             this.RouteValueDictionary.Add(parameterName, string.Empty);
  15.         }
  16.         public override void Process(ModelMetadata modelMetaData)
  17.         {
  18.             modelMetaData.AdditionalValues.Add("AutoCompleteUrlData", this.RouteValueDictionary);
  19.             modelMetaData.TemplateHint = "AutoComplete";
  20.         }
  21.     }
  22. }

As you can see, the constructor takes in strings for the controller, action and parameter name.

The parameter name will be used for passing the search text within the auto complete text box.

The constructor then creates a new RouteValueDictionary which we will use later to construct the url for getting the auto complete results via ajax.

The main interesting method is the method override called Process.

With the process method, the route value dictionary is added to the modelMetaData AdditionalValues collection.

The TemplateHint is also set to AutoComplete, this means that when the view model is parsed for display, the MVC 2 framework will look for a view user control template called AutoComplete, if it finds one, it uses that template to display the property.

The View Model

To show you how the attribute will look, this is the view model I have used in my example which can be downloaded at the end of this post.

View Model
  1. using System.ComponentModel;
  2. using Mvc2Templates.Attributes;
  3. namespace Mvc2Templates.Models
  4. {
  5.     public class TemplateDemoViewModel
  6.     {
  7.         [AutoComplete("Home", "AutoCompleteResult", "searchText")]
  8.         [DisplayName("European Country Search")]
  9.         public string SearchText { get; set; }
  10.     }
  11. }

As you can see, the auto complete attribute is called with the controller name, action name and the name of the action parameter that the search text will be passed into.

The AutoComplete Template

Now all of this is in place, it’s time to create the AutoComplete template.

Create a ViewUserControl called AutoComplete.ascx at the following location within your application – Views/Shared/EditorTemplates/AutoComplete.ascx

Add the following code:

AutoComplete.ascx
  1. <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
  2. <%
  3.     var propertyName = ViewData.ModelMetadata.PropertyName;
  4.     var propertyValue = ViewData.ModelMetadata.Model;
  5.     var id = Guid.NewGuid().ToString();
  6.     RouteValueDictionary urlData =
  7.         (RouteValueDictionary)ViewData.ModelMetadata.AdditionalValues.Where(x => x.Key == "AutoCompleteUrlData").Single().Value;
  8.     var url = Mvc2Templates.Views.Shared.Helpers.RouteHelper.GetUrl(this.ViewContext.RequestContext, urlData);
  9. %>
  10. <input type="text" name="<%= propertyName %>" value="<%= propertyValue %>" id="<%= id %>" class="autoComplete" />
  11. <script type="text/javascript">
  12.     $(function () {
  13.         $("#<%= id %>").autocomplete({
  14.             source: function (request, response) {
  15.                 $.ajax({
  16.                     url: "<%= url %>" + request.term,
  17.                     dataType: "json",
  18.                     success: function (data) {
  19.                         response(data);
  20.                     }
  21.                 });
  22.             },
  23.             minLength: 2
  24.         });
  25.     });
  26. </script>

There is a lot going on in here but when you break it down it’s quite simple.

Firstly, the property name and property value are retrieved through the model meta data. These are required to ensure that the text box input has the correct name and data to allow for model binding. If you look at line 14 you can see them being used in the text box input creation.

The interesting bit is on line 8 and 9, this is the code to retrieve the route value dictionary we added into the model metada via the custom attribute.

Line 11 is used to create the url, in order to do this I created a quick helper class which looks like the code below titled RouteHelper.

The last bit of script is the code to initialise the jQuery UI AutoComplete control with the correct url for calling back to our controller action.

RouteHelper
  1. using System.Web.Mvc;
  2. using System.Web.Routing;
  3. namespace Mvc2Templates.Views.Shared.Helpers
  4. {
  5.     public static class RouteHelper
  6.     {
  7.         const string Controller = "Controller";
  8.         const string Action = "Action";
  9.         const string ReplaceFormatString = "REPLACE{0}";
  10.         public static string GetUrl(RequestContext requestContext, RouteValueDictionary routeValueDictionary)
  11.         {
  12.             RouteValueDictionary urlData = new RouteValueDictionary();
  13.             UrlHelper urlHelper = new UrlHelper(requestContext);
  14.             
  15.             int i = 0;
  16.             foreach(var item in routeValueDictionary)
  17.             {
  18.                 if (item.Value == string.Empty)
  19.                 {
  20.                     i++;
  21.                     urlData.Add(item.Key, string.Format(ReplaceFormatString, i.ToString()));
  22.                 }
  23.                 else
  24.                 {
  25.                     urlData.Add(item.Key, item.Value);
  26.                 }
  27.             }
  28.             var url = urlHelper.RouteUrl(urlData);
  29.             for (int index = 1; index <= i; index++)
  30.             {
  31.                 url = url.Replace(string.Format(ReplaceFormatString, index.ToString()), string.Empty);
  32.             }
  33.             return url;
  34.         }
  35.     }
  36. }

See it in action

All you need to do to see it in action is pass a view model from your controller with the new AutoComplete attribute attached and call the following within your view:

  1. <%= this.Html.EditorForModel() %>

NOTE: The jQuery UI auto complete control expects a JSON string returned from your controller action method… as you can’t use the JsonResult to perform GET requests, use a normal action result, convert your data into json and return it as a string via a ContentResult.

If you download the solution it will be very clear how to handle the controller and action for this demo.

The full source code for this post can be downloaded here.

It has been developed using MVC 2 and Visual Studio 2010.

As always, I hope this has been interesting/useful.

Kind Regards,

Sean McAlinden.

© ASP.net Weblogs or respective owner

Related posts about ASP.NET

Related posts about c#