MVC3 - How to use @ html.checkbox correctly?

I am new to MVC3 and I cannot figure out how to use checkboxes in MVC. I have a bunch of text, in my opinion, how

text1 text2 text3 text4 text5 submitbutton 

This text is not associated with any model with its plain text. I would like to check the box for each item and associate it with the controller so that when the user selects some of the checkbox values ​​and clicks the submit button, my controller selects which items were selected. I tried using @ html.checkbox ("text" + index) and tried the controller

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

But this does not display a list of selected items. Can you tell me what I'm doing wrong or another way to do this?

+4
source share
2 answers

Create a ViewModel with all your values. Fill in the ViewModel and submit it to the view. When something is checked, you will find out what is on this 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 is your friend. You want to have a separate ViewModel for each view, as well as what is passed between the controller and the view. Then you can perform data analysis in the controller or (preferably) at the service level.

Additional Information:
Should ViewModels be used in every view using MVC?

+6
source

What I would do in this situation is to make these elements available to 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 } 
+8
source

Source: https://habr.com/ru/post/1403362/


All Articles