Software Architect / Microsoft MVP (AI) and Technical Author

C#, General Development, MVC

How to implement an autocomplete control with ASP.NET MVC and JSON

Introduction

This post isn’t long and more of a reference.

Sometimes you  want to give the user a better experience when inputting data. Dropdown lists, radio buttons and such enforce data integrity in your web application, an auto-complete mechanism can be handy in situations where you want a little flexibility but at the same time, want to maintain data integrity.

Imagine a list of Cities with an accompanying City Code.

For example, “London (LDN)”

Model

The Model to represent this is basic and only has 3 properties:

 public class City
    {
        public int id { get; set; }
        public string code { get; set; }
        public string name { get; set; }

    }

View

A few things going on here.  The usual suspects, a strongly typed Model, JQuery is imported and we setup a form to post to our Controller.

  1. The script finds the control the user will use to input their value.  The autocomplete event is setup for this.
  2. An AJAX call is made to the Controller method, passing in the value from the input control.
  3. The Controller takes the user input (Prefix), then runs a LINQ query to see if it can find a match and returns this to the user.
@model Models.City
<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>
    <script type="text/javascript">
     
        $(document).ready(function () {
            $("#name").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.id };
                                }))
                            }
                        })
                    },
                });
        })
    </script>

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        <div class="form-horizontal">
            <hr />
            <div class="form-group">
                <div class="col-md-2">
                    @Html.Label("City:")
                </div>
                <div class="col-md-1">
                    @Html.EditorFor(model => model.name, new { htmlAttributes = new { @class = "form-control" } })
                </div>
            </div>
        </div>
    }


Controller

In here, I have a hard coded list of cities and their codes.  You’d probably make a call into your database or application cache here.  The LINQ query uses the Prefix variable and evaluates against the “code” and “name” properties and returns a filtered list which the controller then passes back as a JsonResult.

[HttpPost]
        public JsonResult Index(string Prefix)
        {
            //Note : you can bind same list from database
            List<City> cityList = new List<City>()
            {
                new City {id=1,name="London", code = "LDN" },
                new City {id=2,name="Newcastle Upon Tyne", code = "NCL" },
                new City {id=3,name="Glasgow", code = "GLA" },
                new City {id=4,name="Edinburgh",code = "EDH" },
                new City {id=5,name="Leeds", code = "LDS" },
                new City {id=6,name="Manchester", code = "MAN" },
                new City {id=7,name="Liverpool", code = "LIV" }
        };

            var cities = (from N in cityList
                            where N.name.StartsWith(Prefix) || N.code.Contains(Prefix)
                            select new { N.name });
            return Json(cities, JsonRequestBehavior.AllowGet);

Output

When all of this has been done, data is then rendered for the user to select as they type.  Simple.

autoComplete

JOIN MY EXCLUSIVE EMAIL LIST
Get the latest content and code from the blog posts!
I respect your privacy. No spam. Ever.

Leave a Reply