简体   繁体   English

复选框列表值未绑定到ASP.NET Core MVC中的View GET Request

[英]Checkbox list values are not binding on View GET Request in ASP.NET Core MVC

In my ViewModel I have the following two lists (one is used for showing all available categories in the form and the other is used for just the user selected category values): 在我的ViewModel中,我有以下两个列表(一个用于显示表单中所有可用的类别,另一个用于仅由用户选择的类别值):

public List<CategoryViewModel> Categories{ get; set; }
public List<string> SelectedCategoryValues { get; set; }

In my View I have the following inside of one of my forms: 在我看来,我的一种形式具有以下内容:

@foreach (var category in Model.Categories) {
     <div class="checkbox">
          <label><input type="checkbox" name="SelectedCategoryValues" 
          value="@category.Value">@category.Name</label>
     </div>
}

When submitting the form the model binder is correctly binding SelectedCategoryValues list. 提交表单时,模型绑定器正确绑定了SelectedCategoryValues列表。

However, when loading the page the selected checkboxes are not automatically selecting. 但是,在加载页面时,所选复选框不会自动选中。

The following code is in my Edit GET Action: 以下代码在我的“编辑GET操作”中:

    var vm = new ProductEditViewModel()
    {
        Id = product.Id,
        Name = product.Name,
        Categories = new List<CategoryViewModel>()
        {
            new CategoryViewModel() { Name = "Category 1", Value = "category1" },
            new CategoryViewModel() { Name = "Category 2", Value = "category2" },
            new CategoryViewModel() { Name = "Category 3", Value = "category3" }
        },
        SelectedCategoryValues = productCategories.Select(c => c.Value).ToList()
    };

    return View(vm);

You need to include something like bool IsSelected{get;set;} into CategoryViewModel and assign values in the controller. 您需要在bool IsSelected{get;set;}包含bool IsSelected{get;set;} CategoryViewModel并在控制器中分配值。

var vm = new ProductEditViewModel()
{
    Id = product.Id,
    Name = product.Name,
    Categories = new List<CategoryViewModel>()
    {
        new CategoryViewModel() { Name = "Category 1", Value = "category1",
         IsSelected = productCategories.Where(c => c.Value == "category1").Count() > 0 ? true : false},
         //do the same
        //new CategoryViewModel() { Name = "Category 2", Value = "category2" },
        //new CategoryViewModel() { Name = "Category 3", Value = "category3" }
    },
    //not required
    //SelectedCategoryValues = productCategories.Select(c => c.Value).ToList()
};

return View(vm);

And in the view 并认为

@foreach (var category in Model.Categories) {
     <div class="checkbox">
          <label><input type="checkbox" checked="@category.IsSelected" name="SelectedCategoryValues" 
          value="@category.Value">@category.Name</label>
     </div>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM