Submit Form on CheckBox Click using jQuery in ASP.Net MVC

Last Reply 3 months ago By dharmendr

Posted 3 months ago

hello,

below code works fine, the only problem is i want to submit the form on checkbox list selected event instead of button click so each time checkbox list change uncheck / check it should submit the form

pls advice

@model List<MVCApp.Models.FirstCategories>
@using (@Html.BeginForm("CheckboxListTopcategoryMenu_post", "Application", FormMethod.Get))
{
    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" />
}

 

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

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>