How do I map checkboxes onto MVC model members?

前端 未结 2 1144
走了就别回头了
走了就别回头了 2021-02-07 11:51

I have an MVC view

<%@ Page Language=\"C#\" MasterPageFile=\"PathToMaster\" Inherits=\"System.Web.Mvc.ViewPage\" %>

and

2条回答
  •  臣服心动
    2021-02-07 12:41

    OK, this one will be for MVC3, but - save for syntax changes - should work in MVC2 too. The approach is essentially the same.

    First of all, you should prepare an appropriate (view)model

    public class MyViewModel
    {
        [DisplayName("Option 1")]
        public bool Option1 { get; set; }
    
        [DisplayName("Option 2")]
        public bool Option2 { get; set; }
    }
    

    Then you pass this model to the view you're showing (controller):

    public ActionResult EditMyForm()
    {
        var viewModel = new MyViewModel()
        return View(viewModel);
    }
    

    with the form:

    @model MyViewModel
    @using( Html.BeginForm())
    {
        @Html.Label("Your choice")
    
        @Html.LabelFor(model => model.Option1) // here the 'LabelFor' will show you the name you set with DisplayName attribute
        @Html.CheckBoxFor(model => model.Option1)
    
        @Html.LabelFor(model => model.Option2)
        @Html.CheckBoxFor(model => model.Option2)
        

    }

    Now here the HTML helpers (all the CheckBoxFor, LabelFor, EditorFor etc) allow to bind the data to the model properties.

    Now mind you, an EditorFor when the property is of type bool will give you the check-box in the view, too. :)

    And then, when you submit to the controller, it will auto-bind the values:

    [HttpPost]
    public ActionResult EditMyForm(MyViewModel viewModel)
    {
        //And here the view model's items will be set to true/false, depending what you checked.
    }
    

提交回复
热议问题