Description:
In this example
we explain that how to save multiple Checkboxes values to database in Asp.Net
MVC.or how to Insert Multiple Checkbox List values to database using MVC.or how
to save or insert mutiselect checkbox list values to database using MVC Razor
view.
So here we demonstrate
that how to bind multiple Checkbox List from database and save (Insert) its
selected or checked values to Database in Asp.Net MVC.
public class EmployeeController
: Controller
{
public ActionResult Index()
{
HobbiesEntities
entities = new HobbiesEntities();
return
View(entities.Hobbies.ToList());
}
[HttpPost]
public ActionResult Save(List<Hobby>
hobbies)
{
HobbiesEntities
entities = new HobbiesEntities();
foreach
(Hobby hobby in hobbies)
{
Hobby updatedHobby =
entities.Hobbies.ToList().Find(p => p.HobbyId == hobby.HobbyId);
updatedHobby.IsSelected =
hobby.IsSelected;
}
entities.SaveChanges();
return
RedirectToAction("Index");
}
}
View:
@model List<CheckBoxList_Insert_Database_MVC.Hobby>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Save
(Insert) multiple CheckBoxes (CheckBoxList) values to database in ASP.Net MVC</title>
</head>
<body>
@using (Html.BeginForm("Save",
"Employee", FormMethod.Post))
{
<table>
@for (int i = 0; i <
Model.Count(); i++)
{
<tr>
<td>
@Html.CheckBoxFor(m
=> m[i].IsSelected)
</td>
<td>
@Html.DisplayFor(m
=> m[i].HobbyName)
@Html.HiddenFor(m =>
m[i].HobbyId)
</td>
</tr>
}
</table>
<br/>
<input type="submit" value="Save"/>
}
</body>
</html>
0 comments:
Post a Comment