CodeDigest.Com Logo
Featured:

Creating AutoComplete TextBox in Asp.Net MVC

Tagged as: Asp.Net MVC Posted By

AutoComplete TextBox is a greater way to provide guidance to the users to fill the correct input in a textbox control when the list of option for the input is huge. It can also be used to hint users with the available list of values when the user starts typing. Look at the below image which displays the autocomplete dropdown when we type a.

Moving forward, let’s see how to build auto complete textbox in Asp.Net MVC applications. For demonstration, let’s create an Asp.Net MVC 5.0 application using Visual Studio 2015 (or 2017) and use EntityFramework Code First for data access. We will use jQueryUI for providing the auto complete feature in this article.

 

 

Creating AutoComplete TextBox from Json

Let’s builds an edit Employee page where it has a textbox to input country. We will make this Country textbox to have auto complete feature to assist user with the list of countries when the user starts typing. Refer the below image.

To build this, we need to first get the latest jQueryUI libraray and need a controller action method that could give us the list of countries as JSON for the auto complete plugin. Let’s use Nuget package manager to get the latest jQueryUI packages into project. To do this, right click project in solution explorer and click “Manage Nuget Packages..”. On Browse tab, type “jQuery.UI.Combined” and enter. Click Install to install the library.

Next, let’s develop action method that could return list of countries as JSON sring whose name starts with typed characters in the textbox. The below action method does that.

public ActionResult getcountries(string term)
{
    return Json(db.Countries.Where(c => c.Name.StartsWith(term)).Select(a => new { label = a.Name }), JsonRequestBehavior.AllowGet);
}
 

On Edit.cshtml, let’s include the jQuery UI script and the default stylesheet themes(bolded in below code snippet). We will also enable the auto complete jQueryUI extension for the Country textbox and configure it to fetch the json data from action method.

Edit.cshtml

@section css {

<link href="~/Content/themes/base/jquery-ui.css"
      rel="stylesheet"
      type="text/css" />

}

@* Removed for brevity *@

<div class="form-group">
    @Html.LabelFor(model => model.Country.Name, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Country.Name, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Country.Name, "", new { @class = "text-danger" })
    </div>
</div>

@* Removed for brevity *@

@section Scripts {
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>

<script type="text/javascript">
    $(document).ready(function () {
        $('#Country_Name').autocomplete({
            source: '/employee/getcountries'
        });
    });
</script>
}
 

Assuming you have data in Countries table, execute the application and you can see the auto complete drop down appearing when you start typing on the textbox. The EditorFor() field which binds model.Country.Name will create a textbox with id Country_Name. The full source code attached with this article has data for countries table, you down and execute and see it in action.

Let’s now move ahead and see what other useful customization we can do on the auto complete textbox.

AutoComplete with Label and Id

The above example, we have included only the label in the json, meaning only country names are auto populated. Sometimes, we will have to get the id of the selected value into a hidden field for saving into database i.e. in our case we can have CountryId saved into a hidden field when the Country name is typed in the textbox. This means we can still allow users to type in the country name in Country textbox and save the associated country id into a hidden field to save it to the database.

To do this, we need change the getcountries() action method to return CountryId too in the json. Changed code below.

public ActionResult getcountries(string term)
{
    return Json(db.Countries.Where(c => c.Name.StartsWith(term)).Select(a => new { label = a.Name, id = a.CountryId }), JsonRequestBehavior.AllowGet);
}
 

We can now include select event in the auto complete textbox to save the CountryId in a hidden field. The code below.

Edit.cshtml

@section css {

<link href="~/Content/themes/base/jquery-ui.css"
      rel="stylesheet"
      type="text/css" />
}

@* Removed for brevity *@

<div class="form-group">
    @Html.LabelFor(model => model.Country.Name, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.HiddenFor(model => model.CountryId)
        @Html.EditorFor(model => model.Country.Name, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Country.Name, "", new { @class = "text-danger" })
    </div>
</div>

@* Removed for brevity *@

@section Scripts {
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>

<script type="text/javascript">
    $(document).ready(function () {
        $('#Country_Name').autocomplete({
            source: '/employee/getcountries',
            select: function (event, ui) {
                //set tagids to save
                $("#CountryId").val(ui.item.id);
               

                //Tags for display              
                this.value = ui.item.value;
                return false;
            }

        });
    });
</script>
}
 

Creating Auto Complete From a Hard Coded JavaScript Array

Sometimes, we may have very limited number of values to provide in the auto complete textbox. In this case, we can include the needed values into a javascript array and give the array as source instead of action method that returns the Json. The below code helps us do that.

       <script type="text/javascript">
        $(document).ready(function () {

           var countries = [
             "Afghanistan",
            "Albania",
            "Algeria",
            "AmericanSamoa",
            "Andorra",
            "Angola",
            "Anguilla",
            "Antigua&Barbuda",
            "Argentina",
            "Armenia",
            "Aruba",
            "Australia",
            "Austria"];

           $('#Country_Name').autocomplete({
               source: countries
            });
        });
    </script>
 

 

Download the source and see it in action!



Feedback

Comments

Saving Issue
Thank you for this great tutorial. My only question is when I chose new country then save, it also create new country with the same name but different countryid.
Commented by Arman on 8/13/2020 7:43:20 AM