首页 > 解决方案 > 将复选框列表绑定到 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 });
    }
}

任何帮助将不胜感激。

标签: c#asp.net-mvc

解决方案


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>

这是我通常用来处理复选框的方法


推荐阅读