首页 > 解决方案 > 多个复选框列表数据并提交验证

问题描述

单击提交后,我需要有关如何在列表中保留数据的帮助。在使用数据注释进行提交验证检查期间,我的多个复选框的来源不断被清除。我是网络开发的新手,我不知道如何做到这一点,我只关注互联网上的教程。

在我的创建视图页面上:

@foreach (var item in Model.consideredSUPs)
{               
   <div class="custom-control custom-checkbox" style="margin: 0px 15px">
      <input id="chk@(item.ID)"
         type="checkbox"
         name="FupconsideredList"
         value="@item.Display"
         checked="@item.IsChecked"
         class="custom-control-input">
      <label class="custom-control-label" for="chk@(item.ID)"> @item.Display </label>
   </div>
}
</div>

我的控制器:

public IActionResult Create()
        {
            Questions model = new Questions();

            var checkBoxListItems = new List<ConsideredSUP>();

            checkBoxListItems.Add(new ConsideredSUP() { ID = 1, Display = "Candy wrappers", IsChecked = false });
            checkBoxListItems.Add(new ConsideredSUP() { ID = 2, Display = "Ecobag", IsChecked = false });
            checkBoxListItems.Add(new ConsideredSUP() { ID = 3, Display = "Food packaging", IsChecked = false });
            checkBoxListItems.Add(new ConsideredSUP() { ID = 4, Display = "Plastic bag/Plastic labo", IsChecked = false });
            checkBoxListItems.Add(new ConsideredSUP() { ID = 5, Display = "Straw", IsChecked = false });
            checkBoxListItems.Add(new ConsideredSUP() { ID = 6, Display = "Tumbler", IsChecked = false });
            checkBoxListItems.Add(new ConsideredSUP() { ID = 7, Display = "Water bottles", IsChecked = false });

            model.consideredSUPs = checkBoxListItems;
            return View(model);
}

另外,点击提交后出现数据注释验证时是否称为回发?

标签: asp.netasp.net-mvcentity-frameworkasp.net-core

解决方案


您没有正确地将复选框列表绑定到您的视图模型。请尝试将您的标记修改为:

@for (var i = 0; i < Model.consideredSUPs.Count; i++)
{
    <div class="custom-control custom-checkbox" style="margin: 0px 15px">
        <input type="checkbox" asp-for="@Model.consideredSUPs[i].IsChecked"  class="custom-control-input"/>
        <label asp-for="@Model.consideredSUPs[i].IsChecked" class="custom-control-label">@Model.consideredSUPs[i].Display</label>
        <input type="hidden" asp-for="@Model.consideredSUPs[i].ID" />
        <input type="hidden" asp-for="@Model.consideredSUPs[i].Display" />
    </div>
}

这样在提交到服务器端后,值将绑定到模型,如果验证失败则返回原始页面。

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Questions  questions)
{
    if (ModelState.IsValid)
    {

        return RedirectToAction("pagename");
    }

    return View("index", questions);
}

推荐阅读