How do I map checkboxes onto MVC model members?

前端 未结 2 1188
走了就别回头了
走了就别回头了 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:21

    First you define SelectList for Options. This will be used just to render checkboxes

        public IList OptionsSelectList { get; set; }
    

    Than, you define model that will hold value of single chosen option after post

    public class ChooseOptionViewModel
    {
        public int OptionIdentifier { get; set; } //name or id
        public bool HasBeenChosen { get; set; } //this is mapped to checkbox
    }
    

    Then IList of those options in ModelData

    public IList Options { get; set; }
    

    And finally, the view

        @for (int i = 0; i < Model.OptionsSelectList.Count(); i++)
        {
            
                
                    @Html.Hidden("Options[" + i + "].OptionIdentifier", Model.OptionsSelectList[i].Value)
                
                
                    @Model.OptionsSelectList[i].Text
                
                
                    @Html.CheckBox("Options[" + i + "].HasBeenChosen", Model.Options != null && Model.Options.Any(x => x.OptionIdentifier.ToString().Equals(Model.OptionsSelectList[i].Value) && x.HasBeenChosen))
                
            
        }
    

    After post, you just inspect Options.Where(x => x.HasBeenChosen)

    This is full-functional, and it will allow you to redisplay view when validation errors occur, etc. This seems a bit complicated, but I haven't come up with any better solution than this.

提交回复
热议问题