Autocomplete textbox functionality using Jquery and Asp.net MVC

Autocomplete textbox functionality using Jquery and Asp.net MVC

Introduction

In this article, we will discuss textbox autocomplete functionality using Jquery and MVC. I will use visual studio 2012 framework and SQL server 2008 R2 for this demo.

So, before opening visual studio let’s create and populate student table using following script.

Student table script

create table student (
Id int, 
Name varchar(50),
Gender varchar(50),
City varchar(50)
)
Insert into student values(1,'Sara','Female','Chennai')
Insert into student values(2,'David','Male','Sydeny')
Insert into student values(3,'Dora','Female','New York')
Insert into student values(4,'Maya','Female','London')
Insert into student values(5,'Vikram', 'Male','Mumbai')
Insert into student values(6,'Nikhil','Male','Delhi')

Let’s start for this demo step by step using MVC.

Step 1: Create MVC project, by using following steps.

  • Open Visual Studio.
  • Click on File -> New -> Project.
  • In this project, I am using C# as a programming language, but you can also choose VISUAL BASIC if you know syntaxes of VB.
  • Inside Visual C# -> Web -> Project -> Select Asp.Net MVC 3, 4 or 5 -> Select Ok
  • Now one more dialog box would open -> select Empty as a project template. -> OK.

  • After creating MVC project, you will find list of your project file inside ‘solution explorer’ on your right hand side.

Step 2 : Create an ADO.NET Entity Data Model

  • Right click on your project name -> Add -> New Item.

  • Inside ‘Add New Item’ pop up search and select Ado.Net entity data model- > Name your data model as ‘StudentDataModel’ -> Click Add

  • Next on entity data model -> select generate from database -> click next
  • Next select database connection using new connection button and name your web.config as ‘SampleDBContext’ -> click next

  • Select table from dbo and name your model namespace as ‘Models’ -> click finish

Step 3 : Add new controller

  • Right click on controller folder. Name your controller -> HomeController -> Click on Add button.

  • Add following three methods inside home controller
  • Index get method
[HttpGet]
      public ActionResult Index()
      {
          StudentDbContext DbContext = new StudentDbContext();             
          return View(DbContext.students);
      }
  • Index post method
[HttpPost]
        public ActionResult Index(string searchterm)
        {
            StudentDbContext DbContext = new StudentDbContext();
            List<student> students;
            if (string.IsNullOrEmpty(searchterm))
            {
                students = DbContext.students.ToList();
            }
            else
            {
                students = DbContext.students.Where(x => x.Name.StartsWith(searchterm)).ToList();
            }
            return View(students);
        }
  • Getstudents method
public JsonResult Getstudents(string term)
        {
            StudentDbContext DbContext = new StudentDbContext();
            List<string> students;

            students = DbContext.students.Where(x => x.Name.StartsWith(term)).Select(y => y.Name).ToList();

            return Json(students, JsonRequestBehavior.AllowGet);
        }

Step 4 :Add view

  • Add follwing code in index view
@model IEnumerable<AutocompleteTextboxDemo.Models.student>

@{
    ViewBag.Title = "Index";
}

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

<script type="text/javascript">

    $(function () {
         
        $("#txtsearch").autocomplete({
            
            source: '@Url.Action("Getstudents")'

        });

    })


</script>

<h2>Student Details</h2>


@using (@Html.BeginForm())
{ 
   <b> Student Name </b>
        @Html.TextBox("searchterm", null, new { id="txtsearch"})

        <input type="submit" value="Search" />
}
<table style="border:1px solid">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Gender)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.City)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Gender)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.City)
        </td>
      
    </tr>
}

</table>

Step 5 : Press F5 and see result

Leave a Comment