4

I'm new to MVC3 and I can't figure out how to use checkboxes in MVC. I have a bunch of text in my view like

text1
text2
text3
text4
text5

submitbutton

This text is not related to any model its just plain text. I would like to place a checkbox for each item and a link it to the controller so that when a user selects some of the checkbox values and clicks on the submit button my controller picks up which items have been selected. I tried using @html.checkbox("text"+ index) and tried the controller to be

[HttpPost]
public ActionResult controller(List<string> list)
{
}

But that doesn't pick up the list of selected items. Can you tell me what i'm doing wrong or another way to do it?

user972616
  • 1,324
  • 3
  • 18
  • 38

2 Answers2

8

What i would do in this situation is to make those items to be a property of my ViewModel.

public class MyViewModel
{
  public bool text1  { set;get}
  public bool text2 { set;get;}
  public bool SomeMeaningFullName { set;get;}
  // Other properties for the view
}

and in my Get Action method i will return this ViewModel to my View

public ActionResult Edit()
{
  MyViewModel objVM=new MyViewModel();
  return View(objVM);
}

and in my View

@model MyViewModel

@using (Html.BeginForm("Edit","yourcontroller"))
{
  @Html.LabelFor(Model.text1)
  @Html.CheckBoxFor(Model.text1)
  @Html.LabelFor(Model.text2)
  @Html.CheckBoxFor(Model.text2)

  <input type="submit" value="Save" />
}

Now this property value will be available in your post action method

[HttpPost]
public ActionResult Edit(MyViewModel objVM)
{
 //Here you can access the properties of objVM and do whatever

}
Shyju
  • 214,206
  • 104
  • 411
  • 497
6

Create a ViewModel with all of your values. Populate the ViewModel and send it to the view. When something is checked, you'll know what's what on the post.

public class MyModelViewModel
{
    public List<CheckBoxes> CheckBoxList {get; set;} 
    // etc
}

public class CheckBoxes
{
    public string Text {get; set;} 
    public bool Checked {get; set;}         
}
[HttpPost]
public ActionResult controller(MyModelViewModel model)
{
    foreach(var item in model.CheckBoxList)
    {
        if(item.Checked)
        {
            // do something with item.Text
        }
    }
}

Basically ViewModels are your friend. You want to have a separate ViewModel for each View, and it's what gets passed back and forth between the Controller and the View. You can then do your data parsing either in the controller, or (preferably) in a service layer.

Additional Reference:
Should ViewModels be used in every single View using MVC?

Community
  • 1
  • 1
Chase Florell
  • 46,378
  • 57
  • 186
  • 376