Thursday, June 2, 2011

Dynamic Checkbox for the Data in DB table

We are going to create checkboxes for the items in DB

1. First we need to create the entity for them and create .xsd file

2. Then in city repository we have to retrive the data from table as follows:
public static List<CitiesEntity> GetCitylist()
{
List<CitiesEntity> result = new List<CitiesEntity>();

using (CitiesTableAdapter ta = new CitiesTableAdapter())
{

using (City.CitiesDataTable dt = ta.GetCities())
{
foreach (City.CitiesRow row in dt)
{
CitiesEntity CE = new CitiesEntity();
CE.Cities = row.Cities;
result.Add(CE);
}
return result;
}
}
}

3. Next in Controller we need to call the repository functions as usual
[HttpGet]

public ActionResult GetCheckBox()
{
List<CitiesEntity> Cities = CityRepository.GetCitylist();
ViewData["Chkitems"] = Cities;//Stores list of cities for further reference

return View();
}
 
[HttpPost]

public ActionResult GetCheckBox(FormCollection frm)
{
List<CitiesEntity> Cities = CityRepository.GetCitylist();
ViewData["Chkitems"] = Cities;//Stores list of cities for further reference
int j = Cities.Count;
List<string> cbsource = new List<string>();
string source = "";
for (int i = 0; i <= j; i++)
{
string key = "cbxid" + i.ToString();
if (frm[key] != null)

{
source += frm[key].ToString() + ",";
ViewData["src"] = "You have selected : " + source +".";

//Total datas which have being selected
}
}
return View();
}

4. Here in View we need to import the header files of models and repository as like:<%@ Import Namespace="Jquery.Models"%>
<%@ Import Namespace="Jquery.Repository"%>

then in Html.BeginForm we have to write the following code to display the datas with checkbox<% using(Html.BeginForm())
{ %>

<%int i=0;%>
<%foreach (var item in (IEnumerable<CitiesEntity>)

ViewData["Chkitems"])//Uses the items from DB
{%>
<input type="checkbox" name="cbxid<%=i.ToString()%>" id="cbxid<%=i.ToString()%>" value="<%=item.Cities%>" />

<%=item.Cities%>
<%--<br />--%>
<%i++;%>
<%}%>
<br />

<br />
<br />
<input type="submit" name="Submit" value="Submit" />
<%if (ViewData["src"] != null) //If user selects something
{%>
<%=ViewData["src"]%>
<%}%>
<%}%>

No comments:

Post a Comment