Multiple checkboxes in razor (using foreach)

后端 未结 3 694
失恋的感觉
失恋的感觉 2020-12-06 13:51

I have a problem and I can\'t find solution. I\'m using Razor and it is my VieModel class.

public class GroupToExport
{
    public GroupToExport()
    {
             


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-06 13:56

    You cannot use a foreach loop to generate controls for a collection. The html you're generating for each checkbox (and for the associated hidden input) is . Your model does not contain a property which is named item.

    Use a for loop

    @for(int i = 0; i < Model.ExportingGroups.Count; i++)
    {
      
        
          @Html.CheckBoxFor(m => m.ExportingGroups[i].ToExport)
        
      
    }
    

    Now your HTML will be

    
    
    

    etc. which will correctly bind to your model

    Edit

    Alternatively you can use a custom EditorTemplate for typeof GroupToExport. Create a partial view /Views/Shared/EditorTemplates/GroupToExport.cshtml

    @model yourAssembly.GroupToExport
    
      
        @Html.CheckBoxFor(m => m.ToExport)
      
    
    

    And then in the main view

    @Html.EditorFor(m => m.ExportingGroups)
    

    The EditorFor() method will generate the correct html for each item in your collection based on the template.

提交回复
热议问题