MVC3 - How to correctly use @html.checkbox?

后端 未结 2 541
不思量自难忘°
不思量自难忘° 2021-01-19 18:47

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
         


        
2条回答
  •  日久生厌
    2021-01-19 18:48

    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 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?

提交回复
热议问题