C# 是否将复选框列表绑定到MVC上的编辑视图?
在控制器中编辑 “创建”可以,但无法将所选值从db绑定到“编辑”视图。。它显示复选框,但它们是空的。我知道这里有点不对劲,需要敏锐的目光去捕捉。这对我很有帮助。ThnxC# 是否将复选框列表绑定到MVC上的编辑视图?,c#,asp.net-mvc,C#,Asp.net Mvc,在控制器中编辑 “创建”可以,但无法将所选值从db绑定到“编辑”视图。。它显示复选框,但它们是空的。我知道这里有点不对劲,需要敏锐的目光去捕捉。这对我很有帮助。Thnx [AuthorizeRoles(RoleNames.CanEditCustomer)] public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.Ba
[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" })
<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>
这是我通常处理复选框的方法
问题出在查询中,而不是视图中。请检查您的查询是否从数据库中提取编辑视图的数据。公共CustomerTypeViewModel GetCustomerTypeint?id{var query=SELECT*FROM CustomerType,其中id=@id;return context.GetObjectquery,new{id=id};}
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 });
}
}
<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>