需要使用createView中的选定复选框创建编辑视图
public class CustomerTypeViewModel
{
[Required]
public int? Id { get; set; }
public string Description { get; set; }
[Display(Name = "Please select the Type")]
public bool Selected { get; set; }
}
CustomerView,何时应加载CustomerTypeViewModel列表
public List<CustomerTypeViewModel> SelectedCustomerTypes { get; set; }
private List<CustomerTypeViewModel> selectionList = new List<CustomerTypeViewModel>();
public CustomerViewModel()
{
SelectedCustomerTypes = new List<CustomerTypeViewModel>();
}
public void SetCustomerTypeViewModel(IEnumerable<CustomerTypeViewModel> selected, IEnumerable<CustomerTypeViewModel> all)
{
SelectedCustomerTypes.Clear();
foreach (var item in all)
{
SelectedCustomerTypes.Add(item);
}
foreach (var item in selected)
{
SelectedCustomerTypes.FirstOrDefault(x => x.Description == item.Description).Selected = true;
}
}
public List<CustomerTypeViewModel> GetTipi()
{
return selectionList;
}
在控制器中,我应该调用一个从经理那里获取客户类型的方法
public CustomerTypeViewModel GetCustomerType(int? customerId)
{
var query = "SELECT * FROM CustomerType where Id = @Id";
return context.GetObject<CustomerTypeViewModel>(query, new { Id = customerId });
}
现在在控制器上进行编辑
[AuthorizeRoles(RoleNames.CanEditCustomer)]
public ActionResult Edit(int? id, int? customerId)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var customer = customerManager.Get(customerId);
var vm = new CustomerViewModel();
vm.SetCustomerTypeViewModel(new List<CustomerTypeViewModel>(), customerTypeManager.GetAll());
if (customer == null)
{
return HttpNotFound();
}
return View(customer);
}
有人告诉我在管理器GetCustomerType(customerId)中创建一个方法 <-这是db表中的ID,其中保存了复选框,此方法将加载CustomerTypeViewModel的列表
现在编辑视图
<div class="form-group">
@{
for (int i = 0; i < Model.SelectedCustomerTypes.Count(); i++)
{
<div class="col-md-10">
@Html.Label(Model.SelectedCustomerTypes[i].Description, new { @class = "control-label col-md-2" })
@Html.CheckBoxFor(model => model.SelectedCustomerTypes[i].Selected, new { @checked = "checked" })
@Html.HiddenFor(model => model.SelectedCustomerTypes[i].Id, new { data_val = false })
@Html.HiddenFor(model => model.SelectedCustomerTypes[i].Description, new { data_val = false })
</div>
}
}
</div>
答案 0 :(得分:0)
您需要在控制器中修复GetCustomerType方法。试试这个:
public IActionResult GetCostumerType(int? id)
{
if (id == null)
{
return NotFound();
}
var test = from custom in _yourContext.CustomerType
.Where(p => p.CustomerType.Id == customerId)
select custom;
//change _yourContext with your context variable
if (test == null)
{
return NotFound();
}
return View(test);
}
这样,您将获得与方法中传递的ID相关联的自定义类型。