Monday 16 June 2014

AutoCompeleteExtender TextBox in Mvc 4.0 with Jquery Json

 AutoCompeleteExtender TextBox in Mvc 4.0 with Jquery Json

 use MvcwithJquery

--create table State……………………………………
create  table State
(
StateId int primary key,
StateName varchar(50) unique
)

--insert data in table  state………………………………..

insert into State values(1,'Assam')
insert into State values(2,'Arunachal Pradesh')
insert into State values(3,'Andhra Pradesh')

select *  from State order by stateid

First  we take MvcApplication which name is MvcAutoCompleteExtender   and add Controller in your MVCApplication which name is Home……………….

This code applies for Controller page which name is Home.cs……………….

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
// add this namespace............
using MvcAutoCompleteExtender.Models;

namespace MvcAutoCompleteExtender.Controllers
 {
 public class HomeController : Controller
{
//
// GET: /Home/

public ActionResult Index()
{
return View();
}
MvcwithJqueryEntities1 mm = new MvcwithJqueryEntities1();

//  code for how to get statename from Sql Server using Json…….

public JsonResult GetStateName(string StateName)
{

var v = (from m in mm.States where m.StateName.StartsWith(StateName) select m).ToList();
if (v != null)
{
return Json(v, JsonRequestBehavior.AllowGet);
}
else
return Json("Failed");
}
}
}

This code applies for View page which name is Index.cshtml……………….

@{
ViewBag.Title = "Index";
}
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>

<script src="~/Scripts/jquery-1.7.1.min.js"></script>

<script type="text/javascript">
$(function ()
{
$('#txtstatename').keyup(function () {

$('#2').html('');
var statename = $(this).val();

if (statename != '')
{
$.getJSON('../Home/GetStateName', { StateName: statename }, function (data) {
if (data != null)
{
var div = '';
var no=0;
div+= '<div id="3" style="border:1px solid black; width:150px; height:0px">';
$.each(data, function (i, item) {
no = no + 1;
div += '<a style="text-decoration:none; color:black" href="#" id=' + i + '>' + item.StateName + '</a></br>';
});
var height = no * 20;
div += '</div>';
$('#displaystate').append(div);
$('#3').animate({ height: height });


$('a').click(function (event) {
event.preventDefault();
var id = $(this).attr('id');
var h = $(this).html();
$('#txtstatename').val(h);

}); 
}
}); 
}    
});  
});

</script>
</head>

<body>
<table>
<tr><td><center><b><i>AutoCompeleteExtender in Mvc 4.0 with Jquery Json</i></b></center></td></tr>
<tr><td>State Name</td><td>
<div id="main">
<input type="text" id="txtstatename" placeholder="State Name"  />
</div>
<div id="displaystate" style="height:0px">
</div>
</td></tr>
<tr><td></td><td></td></tr>
</table>
</body>
</html>

Result:



0 comments:

Post a Comment