In this article of ASP.NET MVC we will learn about AutoComplete textbox using ajax and jquery:
Firstly make a connection with database.In my case i have used Entity Model.
Then create a Controller,my case i create HomeController:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using test.Models;
namespace test.Controllers
{
public class HomeController : Controller
{
EmpEntities db = new EmpEntities();
public ActionResult Index()
{
return View();
}
public ActionResult getffvalue(string searchInput)
{
Console.Write("OK");
//Dim list As New List(Of String)()
List<Employee> list = new List<Employee>();
list = db.Database.SqlQuery<Employee>("SELECT * FROM Employee where Name like '%" + searchInput + "%' ").ToList();
return Json(list, JsonRequestBehavior.AllowGet);
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using test.Models;
namespace test.Controllers
{
public class HomeController : Controller
{
EmpEntities db = new EmpEntities();
public ActionResult Index()
{
return View();
}
public ActionResult getffvalue(string searchInput)
{
Console.Write("OK");
//Dim list As New List(Of String)()
List<Employee> list = new List<Employee>();
list = db.Database.SqlQuery<Employee>("SELECT * FROM Employee where Name like '%" + searchInput + "%' ").ToList();
return Json(list, JsonRequestBehavior.AllowGet);
}
}
}
Now Let's create View:
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<input type="text" id="searchInput" />
<script>
$(document).ready(function () {
var ffdata = [];
ffdata.length = 0;
$("#searchInput").autocomplete({
source: function (request, response) {
$.ajax({
url: '@Url.Action("getffvalue", "Home")',
dataType: "json",
data: {
ffvalue: request.term
},
success: function (data) {
// $.each($(data), function () {
for (var i = 0; i < data.length; i++) {
// alert("detailtable:");
ffdata.push({
value: data[i].Name,
label: data[i].Name
});
}
//});
console.log("Datasss" + JSON.stringify(ffdata));
response(ffdata);
},
error: function (response) {
alert("RESPOSNSE TEXT" + response.responseText);
},
failure: function (response) {
alert("RESPOSNSE TEXT failure" + response.responseText);
}
});
},
minLength: 1,
select: function (event, ui) {
//log( "Selected: " + ui.item.value + " aka " + ui.item.category);
//$(".item_value").text(ui.item.label);
//$(".item_cate").text(ui.item.value);
$("#searchInput").val(ui.item.value);
}
});
});
</script>
Comments
Post a Comment