ASP.NET MVC DefaultModelBinder与嵌套列表 [英] ASP.NET MVC DefaultModelBinder with nested lists
问题描述
我有一个表重新presenting员工的时间表视图。跨顶天,项目下侧,与含定期时间和加班时间两个值的每一天/项目交集。
I have a View with a table representing an employee's timesheet. Days across the top, projects down the side, with each day/project intersection containing two values for regular hours and overtime.
在页面模型(简体)类定义是:
The (simplified) class definitions for the page model are:
public class TimesheetFormModel {
public List<Project> Projects;
// other things...
}
public class Project {
public string Name;
public List<WorkUnit> WorkUnits;
}
public class WorkUnit {
public DateTime Date;
public decimal RegularHours;
public decimal OvertimeHours;
}
页面上的表单元素被命名为试图获得DefaultModelBinder拿起他们如下:
The form elements on the page are named as follows in an attempt to get the DefaultModelBinder to pick up on them.
model.Projects[0].Name // "New Project"
model.Projects[0].WorkUnits[0].Date // "5/23/2009 12:00:00 AM"
model.Projects[0].WorkUnits[0].RegularHours // 0
model.Projects[0].WorkUnits[0].OvertimeHours // 0
model.Projects[0].WorkUnits[1].Date // "5/24/2009 12:00:00 AM"
model.Projects[0].WorkUnits[1].RegularHours // 0
model.Projects[0].WorkUnits[1].OvertimeHours // 0
model.Projects[0].WorkUnits[2].Date // "5/25/2009 12:00:00 AM"
model.Projects[0].WorkUnits[2].RegularHours // 0
model.Projects[0].WorkUnits[2].OvertimeHours // 0
// etc.
在该视图但是提交后,模式
参数没有被完全填充。 model.Projects
包含的项目,但项目
的工作单元
字段为空。请问 DefaultModelBinder
支持嵌套集合像我想干什么?如果不是这样,我该怎么办?
When the view is submitted however, the model
parameter isn't being completely populated. model.Projects
contains projects, but the Project
's WorkUnits
field is empty. Does the DefaultModelBinder
support nested collections like I'm trying to do? If not, what should I do?
推荐答案
我终于想通了,为什么 DefaultModelBinder
上的性能并没有拿起 WorkUnit的
:因为他们没有的属性,他们的字段。 DefaultModelBinder
只适用于属性。更改的类定义 WorkUnit的
和项目
使用领域取得的一切点击:
I eventually figured out why DefaultModelBinder
wasn't picking up on the properties of WorkUnit
: Because they weren't properties, they were fields. DefaultModelBinder
only works with properties. Changing the class definition of WorkUnit
and Project
to use fields made everything click:
public class Project {
public IList<WorkUnit> WorkUnits { get; set; }
public string Name { get; set; }
}
public class WorkUnit {
public DateTime Date { get; set; }
public decimal RegularHours { get; set; }
public decimal OvertimeHours { get; set; }
}
(注意:在原来的问题源$ C $ C的Project.Name定义为字段,在我的实际code,这是一个属性这是为什么项目名单得到填充,但工作单元WASN吨。)
(Note: The source code in the original question had Project.Name defined as a field, in my actual code it was a property. This is why the Projects list was getting populated but WorkUnits wasn't.)
这篇关于ASP.NET MVC DefaultModelBinder与嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!