In this tutorial, I am going to explain you how to implement autocomplete textbox in asp.net mvc using jquery ajax. We will be using Visual Studio 2013.
Creating ASP.NET MVC Empty Application
Now the next step is to create ASP.NET MVC empty application as shown below.
Go to File → New → Project. A new window will be open as shown below.
Now go to Web and select .NET Framework 4.5 and give project name and click on OK .
Now new window will open as shown below.
Now Select Empty Template, check on MVC checkbox and click on OK.
Now, a new project will be created as shown below.
Adding Models
Go to Models folder and add new class file Country.cs. Now replace all code with below code.
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Web;
namespace
WebApplication1.Models
{
publicclassCountry
{
publicint ID { get; set; }
publicstring Name { get; set; }
}
}
Adding Controller
Next step is to add controller to application. Go to controller folder and add new empty controller named as Home controller. Replace all code with below code.
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using
WebApplication1.Models;
namespace
WebApplication1.Controllers
{
publicclassHomeController : Controller
{
[HttpGet]
publicActionResult Index()
{
return View();
}
[HttpPost]
publicJsonResult Index(string Prefix)
{
List<Country> countryList = newList<Country>()
{
newCountry {ID=1,Name="India" },
newCountry {ID=2,Name="USA" },
newCountry {ID=3,Name="UK" },
newCountry {ID=4,Name="Austraila" },
newCountry {ID=5,Name="Nepal" },
newCountry {ID=5,Name="Afghanistan" },
newCountry {ID=5,Name="Albania" },
newCountry {ID=5,Name="Andorra" },
newCountry {ID=5,Name="Austria" }
};
var obj = from country in countryList
where
country.Name.StartsWith(Prefix,
StringComparison.OrdinalIgnoreCase)
// use
StartsWith function
// where country.Name.ToLower().Contains(Prefix.ToLower())
// use contains function
selectnew { country.Name };
return Json(obj, JsonRequestBehavior.AllowGet);
}
}
}
Adding View
Now, right click on home controller index action method, add new view and name Index. Select Empty template and uncheck Use layout page and click on Add as shown below.
Now go to Views / Home folder, open Index.cshtml file and replace all code with below code. Here first 3 files are required files i.e jquery.js, jquery-ui.js, jquery-ui.css. And 4th file is bootstrap which is optional.