asp.net - 多个复选框列表数据并提交验证
问题描述
单击提交后,我需要有关如何在列表中保留数据的帮助。在使用数据注释进行提交验证检查期间,我的多个复选框的来源不断被清除。我是网络开发的新手,我不知道如何做到这一点,我只关注互联网上的教程。
在我的创建视图页面上:
@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);
}
另外,点击提交后出现数据注释验证时是否称为回发?
解决方案
您没有正确地将复选框列表绑定到您的视图模型。请尝试将您的标记修改为:
@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);
}
推荐阅读
- java - JPA/Hibernate 只加入一个选定的列
- php - How to insert data from html table to database using laravel
- jmespath - JMESPath - 无法查询另一个列表中的列表中的值
- visual-studio-2019 - 运行“Devenv.exe /setup”命令后 Devenv.exe 崩溃
- flutter - Dart 简单的字符串编码器/解码器
- nuget - Myget 服务器将 Nuget 包许可证显示为 UnKnown
- angular - 如何将 HttpRequest 的值直接返回到变量中
- git - 让git在本地忘记文件但在线记住
- python - 如何在水平 Seaborn 条形图上注释文本?
- c# - MvxObservableCollection 不更新 UI