[英]MVC Model Binding failing when sorting viewmodel elements
I have a working scenario - My viewmodel contains a list of Employee objects. 我有一个工作场景-我的视图模型包含Employee对象的列表。
List<Employee> Employees;
I populate this list by the following: 我通过以下方式填充此列表:
Employees = EmployeeService.GetAll().ToList();
This works fine. 这很好。 I can view the employees, update their data, post back and save to db. 我可以查看员工,更新他们的数据,发回并保存到数据库。
However, when I try and sort the list of Employees in the viewmodel before sending to the view by replacing the code above with: 但是,当我尝试通过将上面的代码替换为:在发送到视图之前,对视图模型中的Employees列表进行排序时:
Employees = EmployeeService.GetAll().OrderBy(e=>e.Name).ToList();
The view is populated nicely with the ordered employee details. 该视图很好地填充了订购的员工详细信息。 Unfortunately when I post back this viewmodel to the controller, the viewmodel.Employees is null / empty. 不幸的是,当我将此视图模型发回给控制器时,viewmodel.Employees为null /空。
I'd appreciate any help if anyone has any ideas what I might be doing wrong here or why this is happening only when I sort. 如果有人对我在这里可能做错的事情有什么想法,或者为什么只有在我进行排序时才会发生这种情况,我将不胜感激。
Regards 问候
Edit-- 编辑 -
public ActionResult Index()
{
EmployeesViewModel _viewModel = new EmployeesViewModel();
return View(_viewModel);
}
[HttpPost]
public ActionResult Index(EmployeesViewModel viewModel)
{
// HERE ** - viewModel.Employees is NULL
EmployeesService.UpdateAllEmployees(viewModel);
return View(viewModel);
}
Edit- Sample Markup -- 编辑-样本标记-
for (int i = 0; i < Model.Employees.Count(); i++)
{
@Html.HiddenFor(e => e.Employees[i].Id)
@Html.HiddenFor(e => e.Employees[i].Name)
<table>
<tr>
<td style = "width: 125px">
@Model.Employees[i].Name
</td>
<td style = "width: 125px">
@Html.CheckBoxFor(e => e.Employees[i].IsActive)
</td>
</tr>
</table>
}
Edit - Class Details 编辑-类详细信息
public class Employee
{
public string Id { get; set; }
public string Name { get; set; }
public string InitialCode { get; set; }
public bool IsActive { get; set; }
public Employee()
{
}
}
public class EmployeesViewModel
{
public List<Employee> Employees { get; set; }
private readonly EmployeesService EmployeesService;
public EmployeesViewModel()
{
Employees = new List<Employee>();
EmployeesService = new EmployeesService();
// Employees = EmployeesService.GetAll().ToList(); //THIS WORKS
Employees = EmployeesService.GetAll().OrderBy(e=>e.Name).ToList();
}
}
EmployeesService simply calls the DB Context and returns all records. EmployeesService只需调用数据库上下文并返回所有记录。
Your HTML form elements need to be rendered in a way that the DefaultModelBinder can correctly parse out the collection. 您的HTML表单元素需要以DefaultModelBinder可以正确解析出集合的方式呈现。 Check out this: https://github.com/danludwig/BeginCollectionItem . 检查一下: https : //github.com/danludwig/BeginCollectionItem 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.