Retain CheckBoxList selection on Form Submit in ASP.Net MVC

Last Reply 3 months ago By dharmendr

Posted 3 months ago

hello,

i have this comma seperated string a = 125, 253, 125  on page load i want to loop that if a value has in checkbox list so it should be checked on checbox list binding

i have this checkbox list binding,

@model List<MVCApp.Models.FirstCategories>
@using (@Html.BeginForm("CheckboxListTopcategoryMenu_post", "Application", FormMethod.Get))
{
    <input type="hidden" id="checkedCheckBoxes" name="checkedHobbies" />
    for (int i = 0; i < Model.Count(); i++)
    {
        @Html.HiddenFor(m => m[i].id)
        @Html.HiddenFor(m => m[i].Title)
        @Html.CheckBoxFor(m => m[i].isSelected)
        @Html.DisplayFor(m => m[i].Title)
    }
<input id="Button2" type="submit" class="btn red" value="Search" />
}

 method to checkboxlist binding

        public ActionResult CheckboxListTopcategoryMenu()
        {
            //Call first category in top category menu partial layout
            //DataTable ds = new DataTable();

            CategoriesBL fc = new CategoriesBL();

            //ds = fc.SelectFirstCategoriesBL();

            //Fille properties of contractIdetails

            return PartialView("CheckboxListTopcategoryMenu", fc.GetCategoriesBL());
        }

 

     public ActionResult CheckboxListTopcategoryMenu_post(List<FirstCategories> categoryselected)
     {
         string _searches = "";
         foreach (FirstCategories cat in categoryselected)
         { 
             if (cat.isSelected)
             {
                 _searches += cat.id.ToString() + ",";
             }
         } 
 
         string url = string.Format("/ads/search?search={0}", _searches);
         return Redirect(url);
         //return View();
     }

 

You are viewing reply posted by: dharmendr 3 months ago.
Posted 3 months ago Modified on 3 months ago

Hi nauna,

Using the article i have created the example.

Save (Insert) multiple CheckBoxes (CheckBoxList) values to database in ASP.Net MVC

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; }
}

Namespaces

using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;

Controller

public class HomeController : Controller
{
    // GET: /Home/
    public ActionResult Index()
    {
        List<HobbyModel> hobbies = GetHobbies();
        return View(hobbies);
    }

    private static List<HobbyModel> GetHobbies()
    {
        List<HobbyModel> hobbies = 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())
                    {
                        hobbies.Add(new HobbyModel
                        {
                            Id = Convert.ToInt32(sdr["HobbyId"]),
                            Name = sdr["Hobby"].ToString(),
                            IsSelected = Convert.ToBoolean(sdr["IsSelected"])
                        });
                    }
                }
                con.Close();
            }
        }

        return hobbies;
    }

    [HttpPost]
    public ActionResult Save(List<HobbyModel> selected)
    {
        string _searches = "";
        foreach (HobbyModel hobby in selected)
        {
            if (hobby.IsSelected)
            {
                _searches += hobby.Id.ToString() + ",";
            }
        }
        string url = string.Format("/Home/Search?search={0}", _searches);
        return Redirect(url);
    }

    public ActionResult Search()
    {
        List<HobbyModel> hobbies = GetHobbies();
        string[] checkedHobbyId = Request.QueryString["search"].Split(',');
        for (int i = 0; i < hobbies.Count; i++)
        {
            HobbyModel hobby = hobbies[i];
            for (int j = 0; j < checkedHobbyId.Length - 1; j++)
            {
                if (hobby.Id == Convert.ToInt32(checkedHobbyId[j]))
                {
                    hobby.IsSelected = true;
                    break;
                }
            }
        }
        // Returning updated model.
        // You can return PartialView with the Updated model.
        return View(hobbies);
    }
}

View

Index

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<IEnumerable<HobbyModel>>" %>

<%@ Import Namespace="_Comma_Seperated_Value_Checked.Models" %>
<!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>
</head>
<body>
    <%using (Html.BeginForm("Save", "Home", FormMethod.Post))
      {%>
    <table>
        <%for (int i = 0; i < Model.Count(); i++)
          {%>
        <tr>
            <td>
                <%:Html.HiddenFor(m => ((List<HobbyModel>)Model)[i].Id)%>
                <%:Html.CheckBoxFor(m => ((List<HobbyModel>)Model)[i].IsSelected, new { onclick = "this.form.submit()" })%>
                <%:Html.DisplayFor(m => ((List<HobbyModel>)Model)[i].Name)%>
            </td>
        </tr>
        <%}%>
    </table>
    <%} %>
</body>
</html>

Search

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<IEnumerable<HobbyModel>>" %>

<%@ Import Namespace="_Comma_Seperated_Value_Checked.Models" %>
<!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>Search</title>
</head>
<body>
    <table>
        <%for (int i = 0; i < Model.Count(); i++)
          {%>
        <tr>
            <td>
                <%:Html.HiddenFor(m => ((List<HobbyModel>)Model)[i].Id)%>
                <%:Html.CheckBoxFor(m => ((List<HobbyModel>)Model)[i].IsSelected)%>
                <%:Html.DisplayFor(m => ((List<HobbyModel>)Model)[i].Name)%>
            </td>
        </tr>
        <%}%>
    </table>
</body>
</html>

Screenshot