In this article we have learn how to handle checkbox list values in MVC Asp.Net .There are two ways
1)
Custom
2)
Install-Package MvcCheckBoxList
Custom
So we have class “employeeDepartment” contains Id and department as given below
public
class
EmployeeDepartment
{
public
int Id {
get;
set; }
public
string Department {
get;
set; }
}
In controller we have crate actionresult index method
public
ActionResult Index()
{
var emp =
new
List<EmployeeDepartment>{
new
EmployeeDepartment{ Id =1,Department="CSD"
},
new
EmployeeDepartment { Id=2, Department="IT"},
new
EmployeeDepartment { Id=3, Department="HouseKeeping"},
new
EmployeeDepartment { Id=4, Department="HR"},
};
return
View(emp);
}
In this method we have create strongly type as employee department.So I have created a view “Index”
@model
List<EmployeeDepartment>
@using
(Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<table>
<tbody>
@for
(var i = 0; i < Model.ToList().Count(); i++)
{
<tr>
<td><p><span>
<input
type="checkbox"
name="emp"
value="@Model[i].Id"
/>
</span><span>
@Model[i].Department</span>
</p>
</td>
</tr>
}
</tbody>
</table>
<button
id="btnSave"
value="Save"
type="submit"></button>
}
So
here I am bind checkbox values mvc Asp.net. In MVC by default
checkboxlist control not available. You have to install third party
plugin. So next
question how to get posted value of checkbox list. So the values of the
checkboxes checked can be retrieved using the following controller code
as given below
[HttpPost]
public
ActionResult Index(FormCollection
frm)
{
var selectedEmpIds= frm["emp"].ToString();//1,2,3
return View();
}
2)
Install-Package MvcCheckBoxList
after the install of package . You have simply replace for loop with this code as given below
@Html.CheckBoxList("emp",
model => model,//list item
entity => entity.Id,
entity => entity.Department,
model =>
null //selected value null frist time)
No comments:
Post a Comment