Valter
Valter

Reputation: 2899

MVC3 Passing dictionary<string,bool> from view to controller

I need to display a few checkbox on a form and the user can check as many as hey want.

So I store the checkbox options on Database. (required)

Model

public class Options
{
    public int OptionsId {get; set;}
    public string Option {get; set;}
}

On the viewModel,

IEnumerable<Options> listCheckBoxOptions {get; set;}// store list of options from database
Dictionary<string,bool> checkboxs {get; set;} // store if is check or not

So on the view i want to store the check box value (true/false) in this checkboxs dictionary.

@foreach (var x in Model.listCheckBoxOptions)
     {                  
           @Html.CheckBoxFor(m => m.checkboxs[x.Option])
           @m.Option <br />                             
     } 

So when i submit the form... the checkboxs is null when gets to the controller.

Any idea why?

Upvotes: 3

Views: 3429

Answers (2)

Shyju
Shyju

Reputation: 218722

Use Editor Template

Add one more property to your ViewModel. For Better Readability, I am going to change the name from plural to singular (Options to Option)

public class Option
{
    public int OptionId {get; set;}
    public string Option {get; set;}
    public bool IsSelected { set;get;}
}

And your Main ViewModel,

public class CustomerViewModel
{
  public IEnumerable<Option> OptionList { set;get;}
  public CustomerViewModel()
  {
     OptionList=new List<Option>();
  }
}

Create a View called Option.cshtml under Views/YourControllerName folder.

Have this content inside that.

@model Option
@{
   Layout = null;
}
<p>
 @Html.CheckBoxFor(x => x.IsSelected)
 @Html.LabelFor(x => x.IsSelected, Model.Option)
 @Html.HiddenFor(x => x.OptionId)
</p>

And in the Main form, Call it like this

@model YourViewModel
@using(Html.BeginForm())
{     
   @Html.EditorFor(m=>m.OptionList)
  <input type="submit" value="Save" />
}

Now in your POST action, you can check the IsSelected property value of items in the OptionList property

[HttpPost]
public ActionResult Edit(CustomerViewModel model)
{
   foreach(var opt in model.OptionList)
   {
      //check for model.IsSelected value for each item
   }
}

Upvotes: 1

Simon Whitehead
Simon Whitehead

Reputation: 65059

Your checkboxes will be given names like this checkboxs[key here] and ID's like this checkboxs_key_here_. MVC doesn't know how to bind these back.

Have a look at this thread that I answered just days ago: Generating an MVC3 RadioButton list in a loop statement

It's the same thing, just using RadioButtons instead of CheckBoxes.

Upvotes: 1

Related Questions