In this article I will explain with an example, how to implement jQuery AutoComplete TextBox using Web API in ASP.Net MVC Razor.
The jQuery AutoComplete TextBox data will call the Web API which will fetch the data from database using Entity Framework in ASP.Net MVC Razor.
Note: For beginners in ASP.Net MVC, please refer my article ASP.Net MVC Hello World Tutorial with Sample Program example.
 
 
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
 
 
Creating an Entity Data Model
The very first step is to create an ASP.Net MVC Application and connect it to the Northwind Database using Entity Framework.
Note: For more details please refer my article ASP.Net MVC: Simple Entity Framework Tutorial with example.
 
Following is the Entity Data Model of the Customers Table of the Northwind Database which will be used later in this project.
Implement jQuery AutoComplete TextBox using Web API in ASP.Net MVC
 
 
Model
The CustomerModel class consists of the following property.
public class CustomerModel
{
    ///<summary>
    /// Gets or sets Name.
    ///</summary>
    public string Name { get; set; }
}
 
 
Web API Controller
In order to add a Web API Controller you will need to Right Click the Controllers folder in the Solution Explorer and click on Add and then Controller.
Now from the Add Scaffold window, choose the Web API 2 Controller – Empty option as shown below.
Implement jQuery AutoComplete TextBox using Web API in ASP.Net MVC
 
Then give it a suitable name and click Add.
Implement jQuery AutoComplete TextBox using Web API in ASP.Net MVC
 
The next task is to register the Configuration for Web API in the Global.asax file so that the Web API is available for accessing on Web.
In order to do so open Global.asax file and add the following line.
System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);
 
Make sure you add it in the same order as shown below.
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }
}
 
The next step is to code the Web API Controller. The Web API Controller consists of a method named GetCustomers which accepts an object of CustomerModel.
This method is decorated with Route attribute which defines its Route for calling the Web API method and HttpPost attribute which signifies that the method will accept Http Post requests.
The records of the Customers are fetched using Entity Framework and are filtered using the StartsWith function based on the value of the Name property.
Finally the records are returned as an Anonymous object containing a list of Key Value Pairs i.e. the ID and the Name of the Customer.
Note: For more details on displaying returning Anonymous type from Web API, please refer my article Return Anonymous type from Web API in ASP.Net MVC.
 
public class CustomerAPIController : ApiController
{
    [Route("api/CustomerAPI/GetCustomers")]
    [HttpPost]
    public HttpResponseMessage GetCustomers(CustomerModel customer)
    {
        NorthwindEntities entities = new NorthwindEntities();
        var customers = (from c in entities.Customers
                         where c.ContactName.StartsWith(customer.Name)
                         select new
                         {
                             label = c.ContactName,
                             val = c.CustomerID
                         }).ToList();
 
        return Request.CreateResponse(HttpStatusCode.OK, customers);
    }
}
 
 
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
 
Action method for handling POST operation
This Action method handles the Form submission and displays the ID and Name of the selected Customer in jQuery AutoComplete using ViewBag object.
Note: For more details on displaying message from Controller to View, please refer my article Display (Pass) String Message from Controller to View in ASP.Net MVC.
 
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public ActionResult Index(string CustomerName, string CustomerId)
    {
        ViewBag.Message = "CustomerName: " + CustomerName + " CustomerId: " + CustomerId;
        return View();
    }
}
 
 
View
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The Form consists of three elements i.e. a TextBox (implemented as AutoComplete), a Hidden Field (for saving the Value part of the Autocomplete Item) and a Submit Button.
The jQuery AutoComplete plugin has been applied to the TextBox and the URL of the plugin is set to the Action method of the Web API.
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
    <style type="text/css">
        body {
            font-family: Arial;
            font-size: 10pt;
        }
    </style>
</head>
<body>
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js" type="text/javascript"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
    <link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css"
          rel="Stylesheet" type="text/css"/>
    <script type="text/javascript">
        $(function () {
            $("#txtCustomer").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '/api/CustomerAPI/GetCustomers',
                        data: "{ name: '" + request.term + "'}",
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        success: function (data) {
                            response($.map(data, function (item) {
                                return item;
                            }))
                        },
                        error: function (response) {
                            alert(response.responseText);
                        },
                        failure: function (response) {
                            alert(response.responseText);
                        }
                    });
                },
                select: function (e, i) {
                    $("#hfCustomer").val(i.item.val);
                },
                minLength: 1
            });
        });
    </script>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        <input type="text" id="txtCustomer" name="CustomerName"/>
        <input type="hidden" id="hfCustomer" name="CustomerId"/>
        <br/><br/>
        <input type="submit" id="btnSubmit" value="Submit"/>
        <br/><br/>
        @ViewBag.Message
    }
</body>
</html>
 
 
Screenshot
Implement jQuery AutoComplete TextBox using Web API in ASP.Net MVC
 
 
Downloads