How do I bind checkboxes to the List property of a view model?

后端 未结 4 1453
暗喜
暗喜 2020-12-11 18:35

I\'ve been reading the various posts on view models and check boxes, but my brain is starting to lock up and I need a little push in the right direction.

Here\'s my

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-11 19:16

    Part of My View Model:

    public List UserChannelIds { get; set; }
    
    public List SharedChannelIds { get; set; }
    
    public List Weekdays { get; set; }
    
    public MyViewModel()
    {
        UserChannelIds = new List();
        SharedChannelIds = new List();
        Weekdays = new List();
    }
    

    I used partial views to display my reusable checkboxes (I didn't know about editor templates at this point):

    @using AlertsProcessor
    @using WngAlertingPortal.Code
    @model List
    @{
        var sChannels = new List();
        Utility.LoadSharedChannels(sChannels);
    }
    
    

    Shared Channels:

      @{ foreach (var c in sChannels) { string chk = (Model.Contains(c.SharedChannelId)) ? "checked=\"checked\"" : "";
    • @c.Description (@c.Channel)
    • } }

    All three checkbox partial views are similar to each other. The values of the checkboxes are integers, so by lining up my view model List names with the checkbox names, the binding works.

    Because I am working in int values, I don't feel like I need the extra class to represent the checkboxes. Only checked checkboxes get sent, so I don't need to verify they are checked; I just want the sent values. By initializing the List in the constructor, I should be avoiding null exceptions.

    Is this better, worse or just as good as the other solution? Is the other solution (involving an extra class) best practice?

    The following articles were helpful to me:

    http://forums.asp.net/t/1779915.aspx/1?Checkbox+in+MVC3

    http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

提交回复
热议问题