MVC3 - How to correctly use @html.checkbox?

后端 未结 2 520
不思量自难忘°
不思量自难忘° 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:57

    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)
    
      
    }
    

    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
    
    }
    

提交回复
热议问题