-1

I have added a code to fetch values from a database to show multiple checkboxes as shown below on my view page

@{
    var dept_list = ViewBag.department_list;
}
@foreach (var dept_item in dept_list)
{
    <input type="checkbox" id="dept_checkbox" name="@dept_item.name" value="@dept_item.department_ID" />
    <span class="rmargin20">@dept_item.name</span>
}

Now I want to get the values of the checked checkboxes, and want to save these values to the database. The above mentioned code will generate the checkboxes for each record in database.

This can be done in asp.net. But i want to implement this feature in MVC.

Akhilesh Sehgal
  • 186
  • 3
  • 16
  • Suggest you refer [this answer](http://stackoverflow.com/questions/29542107/pass-list-of-checkboxes-into-view-and-pull-out-ienumerable/29554416#29554416). Alternatively you could give each checkbox `name="departments"` and in the POST method have a parameter `IEnumerable departments` –  Jul 13 '16 at 07:28

2 Answers2

0

Hi You can use FormCollection for getting the form values.. see my below sample code :

    public ActionResult MethodName(FormCollection form)
                {
                    string CheckboxValue = form.Get("CheckBoxName_1"); //Dynamic checkbox name
                    return View();
                }

Hope it helps you :)

Sunil Kumar
  • 3,142
  • 1
  • 19
  • 33
-1

if your view is strongly binds then just submit the form and get the checked value using above solution.

And if it is not then using jquery to save checked values.

use a class for each check box

<input type="checkbox" id="dept_checkbox" class="checkbox_dept" name="@dept_item.name" value="@dept_item.department_ID" />

<span class="rmargin20">@dept_item.name</span>

Now get checked values

var selectedDepts == null;

     $('.checkbox_dept::checked').each(function (e) {
            selectedDepts += this.value + "^";
        });


           //ajax call
            $.post("../ControlerName/Save", { "strSelectedDepts": selectedDepts },
        function (data) {
                  //saved successfully
              }.fail(function (xhr, textStatus, errorThrown) {
                //Error occured 
            });

in your controller file.

[HttpPost]
public string Save(string strSelectedDepts)
 {
 //remove last ^ char
 string strData = strSelectedDepts.Substring(0, strSelectedDepts.Length - 1);

  string[] arrData = strData.Split('^');
  foreach(var itm in arrData)
   {
    //do save operation
    }
}
mmushtaq
  • 3,430
  • 7
  • 30
  • 47