ASP.NET MVC 不知道如何将 DepartmentId 表单值转换为 Department.Load(DepartmentId) 调用。为此,您需要为您的模型实现一个活页夹。
[ActiveRecord("Employees")]
[ModelBinder(EmployeeBinder]
public class Employee : ActiveRecordBase<Employee>
{
[PrimaryKey]
public int EmployeeId
{
get;
set;
}
[BelongsTo(NotNull = true)]
public Department Department
{
get;
set;
}
// ...
}
EmployeeBinder 负责将路由/表单数据转换为对象。
public class EmployeeBinder : IModelBinder
{
#region IModelBinder Members
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
// ...
if (controllerContext.HttpContext.Request.Form.AllKeys.Contains("DepartmentId"))
{
// The Department Id was passed, call find
employee.Department = Department.Find(Convert.ToInt32(controllerContext.HttpContext.Request.Form["DepartmentId"]));
}
// ...
}
#endregion
}
有了这个,只要一个 Employee 被用作一个动作的参数,活页夹就会被调用。
public ActionResult Create(Employee employee)
{
// Do stuff with your bound and loaded employee object!
}
有关详细信息,请参阅此博客文章