Description:-
In this Example I explain that How to Bind Data to Checkbox List
from sqlserver database or Create Checkbox list in mvc4 or how to Implement or
use checkbox in MVC4. We already explain that How to Bind Checkbox list in
asp.Net but in MVC that is different way to Bind Checkbox list.
how to upload image in database have a datatype is Image upload image with image datatype
How to create or generate Captcha code in asp.net captcha code same like Google in asp.net
Here we create a model class Category with three properties with
name like id, name and selected and one
static method that will return the List of all Category.
Category.cs:-
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
namespace
Sample.Models
{
public
class Category
{
public
int ID { get; set; }
public
string Name { get; set; }
public
bool IsSelected{ get; set; }
public
static
List<Category>
getCategory()
{
List<Category>
category = new List<Category>()
{
new
Category() { ID =1, Name="Cat1", IsSelected = true },
new
Category() { ID =2, Name="Cat2", IsSelected = false },
new
Category() { ID =3, Name="Cat3", IsSelected = true },
new
Category() { ID =4, Name="Cat4", IsSelected = false },
new
Category() { ID =5, Name="Cat5", IsSelected = true },
new
Category() { ID =6, Name="Cat6", IsSelected = false },
new
Category() { ID =7, Name="Cat7", IsSelected = true },
new
Category() { ID =8, Name="Cat8", IsSelected = false },
};
return
category;
}
}
}
Now we will create a productcontroller in which Index()
ActionResult method will returns all the Category List that we are added in
model category class.
ProductCategoryController.cs:-
namespace
Sample.Controllers
{
public
class ProductCategoryController : Controller
{
public
ActionResult Index()
{
List<Category>
model = new List<Category>();
model
= Category.getCategory();
return
View(model);
}
}
}
Now finally how to bind all Category in CheckBoxList in
Razor view. Here we implement code to bind all category to checkboxlist in
Razor view. Here we create a view with model list of category.here we use two
hiddenfield for store the checkbox status that checked or unchecked.
The most
important thing that keep in your mind, when you create @Html.CheckBox it will automatically create a hiddenfield for this
checkbox and also maintain the status of the checkbox that checked or
unchecked, but when we use
@Html.CheckBoxFor() then we have to explicitally define the
hiddenfield to store the status of the checkbox.
Index. Cshtml:-
@model
List<Sample.Models.Category>
@{
ViewBag.Title
= "Index";
Layout
= "~/Views/Shared/_Layout.cshtml";
}
<h2>Category</h2>
@using
(Html.BeginForm("Index", "ProductCategory",
FormMethod.Post))
{
for
(int i = 0; i < Model.Count; i++)
{
@Html.CheckBoxFor(m
=> m[i].IsSelected)
@Html.Label(Model[i].Name);
@Html.HiddenFor(m
=> m[i].Name)
@Html.HiddenFor(m
=> m[i].ID)
<br
/>
}
<div>
<input type="submit"
value="Go!"
/></div>
}
0 comments:
Post a Comment