MVC CheckBoxList model binding with non boolean

前端 未结 4 1231
清歌不尽
清歌不尽 2021-01-13 04:37

I want to bind a List to CheckBox and get the selected values. I need to display two such Checkbox tables and have to retrieve both the IDs.

Below is my ViewModel

4条回答
  •  南方客
    南方客 (楼主)
    2021-01-13 04:51

    you should add a third bool property to both of your models,

      public bool IsSelected { get; set; }
    

    and set it defaulted to false, and will get it true on posting back when you check the corresponding check box, and depending upon true values you can do what ever you want with corresponding selected values and texts as well

    here is my code which i have used some where to acheive the same:

                        
                            @{int i = 0;
                            }
                            @foreach (var item in Model.SurfaceTypeList)
                            {
    
                                
                                
                                
                                @Html.Label(item.Text)
                                

    i++; }

    model contains a property:

    public List SurfaceTypeList { get; set; }
    public class SurfaceType
    {
    public bool IsSelected { get; set; }
        public string Text { get; set; }
        public string Value { get; set; }
    }
    

    and here is how i retrieved the text/values:

      foreach (var item in modelData.SurfaceTypeList)
                {
                    if (item.IsSelected)
                    {
                        var surfaceType = new XElement("SurfaceType");
                        var id = new XElement("Id");
                        id.Add(item.Value);
                        surfaceType.Add(id);
                        var i = id.Value;
                        surfaceTypeList.Add(surfaceType);
                    }
    
                }
    

提交回复
热议问题