Thursday, June 2, 2011

Auto Complete Textbox in MVC

Here is Auto complete textbox for city names witth reference to the cities stored in particular DB

The following are the steps to follow:

1. Define the Entity for the "city" field in the Repository folder

2. Next we need to add the Dataset for the DB with the apprpriate query to retrive data for the autocomplete textbox

3. In repository we have to write the code to connect with database
Here is the code:
public static List<CityEntity> GetCity(string TNCity)//Text in the textbox as parameter which will be passed as an variable in Stored proc.
{
List<CityEntity> result = new List<CityEntity>();
using (tblCitiesTableAdapter ta = new tblCitiesTableAdapter())
{
using (City.tblCitiesDataTable dt = ta.GetCityName(TNCity))
{
foreach (City.tblCitiesRow row in dt)
{
CityEntity CE = new CityEntity();
CE.City = row.City;
result.Add(CE);
}
return result;
}
}
}


4. In controller we have to cal the repository function
//This is called in master page action link
public ActionResult Cities()
{
return View();
}

//This is called in autocomplete function of the view
public ActionResult City(string q)
{
try{
string[] City = GetCity(q);

return Content(string.Join("\n", City));
}
catch( Exception ex)
{
throw ex;
}
}

//This is called in the previous function

public string[] GetCity(string TNCity)
{
try{
List<CityEntity> resultCity = CityRepository.GetCity(TNCity);

string[] src = new string[resultCity.Count];
int i = 0;
foreach (CityEntity cct in resultCity)
{
src[i] = cct.City;
i++;
}
return src;
}
catch(Exception e)
{
throw e;
}
}

5.the final step is view in which we need to give the URL for autocomplete action
<%=Html.TextBox("txtCity")%>

<script language="javascript" type="text/javascript">$(
$(function () { '#txtCity').autocomplete('<%=Url.Action("City","Home") %>',

autoFill:true
});
});
</script>

No comments:

Post a Comment