c# - 将复选框列表绑定到 MVC 上的编辑视图?
问题描述
在控制器中编辑
创建是好的,但不能将选定的值从 db 绑定到编辑视图。它显示复选框,但它们是空的。我知道这里有一点小问题,需要敏锐的眼光才能抓住它。这会对我有很大帮助。谢谢
[AuthorizeRoles(RoleNames.CanEditCustomer)]
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var customer = customerManager.Get(id);
if (customer == null)
{
return HttpNotFound();
}
var vm = new CustomerViewModel();
vm.GetCustomerTypeViewModel(new List<CustomerTypeViewModel>(), customerTypeManager.GetAll());
return View(vm);
}
编辑视图
<div class="form-group">
@{
for (int i = 0; i < Model.GetCustomerType.Count(); i++)
{
<div class="col-md-10">
@Html.Label(Model.GetCustomerType[i].Description, new { @class = "control-label col-md-2" })
@Html.CheckBoxFor(model => model.GetCustomerType[i].Selected)
@Html.HiddenFor(model => model.GetCustomerType[i].Id)
@Html.HiddenFor(model => model.GetCustomerType[i].Description)
</div>
}
}
</div>
视图模型
public List<CustomerTypeViewModel> GetCustomerType { get; set; }
public void GetCustomerTypeViewModel(IEnumerable<CustomerTypeViewModel> selected, IEnumerable<CustomerTypeViewModel> all)
{
foreach (var item in all)
{
GetCustomerType.Add(item);
}
foreach (var item in selected)
{
GetCustomerType.FirstOrDefault(x => x.Description == item.Description).Selected = true;
}
}
经理
private void InsertOrUpdateCustomerTypes(int? customerId, IEnumerable<int?> customerTypeIds)
{
var query = "Delete FROM CustomerCheckedType WHERE customerId = @customerId";
context.Execute(query, new { customerId });
query = "INSERT INTO CustomerCheckedType (customerId, customerTypeId) VALUES (@customerId, @customerTypeId)";
foreach (var customerTypeId in customerTypeIds)
{
context.Execute(query, new { customerId, customerTypeId });
}
}
任何帮助将不胜感激。
解决方案
你Edit View
应该如下:
<div class="form-group">
@{
for (int i = 0; i < Model.GetCustomerType.Count(); i++)
{
<div class="col-md-10">
@Html.Label(Model.GetCustomerType[i].Description, new { @class = "control-label col-md-2" })
<input type="checkbox" name="selectedCustomerTypes" value="@Model.GetCustomerType[i].Id"
@if (Model.GetCustomerType[i].Selected)
{
<text> Checked</text>
}/>
@Html.HiddenFor(model => model.GetCustomerType[i].Id)
@Html.HiddenFor(model => model.GetCustomerType[i].Description)
</div>
}
}
</div>
这是我通常用来处理复选框的方法
推荐阅读
- python - 如何修复错误“_core.QgsProcessingException:执行算法时出错。”
- regex - 在 Oracle 中替换子字符串时如何替换转义特殊字符?
- python - 如何在谷歌的广度和深度模型中实现跨产品转换
- pandas - 如何使我的 x 标签在几个月内增加?
- visual-studio - Visual Studio 的 /experimental:module 与 Vulkan 的 core.h 冲突导致语法错误 - 编译失败
- c# - 同时等待多个具有独立延续的 WCF 异步调用
- mysql - LEFT JOIN 到 INNER JOIN 多个表
- pyspark - 计算来自 RDD 的不同用户
- java - 我的代码在通过命令行执行时没有执行,而从 Eclipse 成功运行
- javascript - 为什么我的画布签名不起作用?我必须在面向对象的 javascript 中做到这一点。非面向对象中的相同代码正在工作