Hi nauna,
Using the article i have created the example.
Check this example. Now please take its reference and correct your code.
Model
public class HobbyModel
{
public bool IsSelected { get; set; }
public int Id { get; set; }
public string Name { get; set; }
}
Controller
public class HomeController : Controller
{
// GET: /Home/
public ActionResult Index()
{
List<HobbyModel> hobbies = GetHobbies();
return View(hobbies);
}
private static List<HobbyModel> GetHobbies()
{
List<HobbyModel> items = new List<HobbyModel>();
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "SELECT HobbyId,Hobby,IsSelected FROM Hobbies";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
items.Add(new HobbyModel
{
Id = Convert.ToInt32(sdr["HobbyId"]),
Name = sdr["Hobby"].ToString(),
IsSelected = Convert.ToBoolean(sdr["IsSelected"])
});
}
}
con.Close();
}
}
return items;
}
[HttpPost]
public ActionResult Index(string checkedHobbies)
{
string[] checkedCheckBoxes = checkedHobbies.Split(',');
List<HobbyModel> hobbies = GetHobbies();
for (int i = 0; i < hobbies.Count; i++)
{
HobbyModel hobby = hobbies[i];
for (int j = 0; j < checkedCheckBoxes.Length - 1; j++)
{
if (hobby.Id == Convert.ToInt32(checkedCheckBoxes[j]))
{
hobby.IsSelected = true;
break;
}
}
}
return View(hobbies);
}
}
View
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<IEnumerable<_Submit_Form_CheckBox_Checked_MVC.Models.HobbyModel>>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Index</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("input[type=checkBox]").on('click', function () {
var hobbies = "";
$("input[type=checkbox]:checked").each(function (index, item) {
hobbies += $(item).closest('tr').find('#item_Id').val() + ",";
});
$('#checkedCheckBoxes').val(hobbies);
this.form.submit();
});
});
</script>
</head>
<body>
<%using (Html.BeginForm("Index", "Home", FormMethod.Post))
{%>
<input type="hidden" id="checkedCheckBoxes" name="checkedHobbies" />
<table>
<%foreach (var item in Model)
{%>
<tr>
<td>
<%:Html.CheckBoxFor(m => item.IsSelected)%>
<%:Html.DisplayFor(m => item.Name)%>
<%:Html.HiddenFor(m => item.Id)%>
</td>
</tr>
<%} %>
</table>
<%} %>
</body>
</html>