如何使用 DefaultModelBinder 绑定模型属性 - ASP.NET MVC2
我有以下场景。
- 我的“编辑/员工”视图填充了来自实体框架实体(员工)的模型,
- 我从“编辑/员工”发布到“保存/员工”控制器操作。 Save/Employee 操作需要另一种具有 Employee 作为属性的类型 (EmployeeSave)
这是 Edit/Employee 方法
public ActionResult Edit(EmployeesEdit command)
{
var employee = command.Execute();
if (employee != null)
{
return View(employee);
}
return View("Index");
}
这是 Save/Employee 方法
public ActionResult Save(EmployeesSave command)
{
var result = command.Execute();
if (result)
{
return View(command.Employee);
}
return View("Error");
}
这是 EmployeeSave 类
public class EmployeesSave
{
public bool Execute()
{
// ... save the employee
return true;
}
//I want this prop populated by my model binder
public Employee Employee { get; set; }
}
MVC DefaultModelBinder 能够解析 Employee 和 EmployeeSave 类。
I have the following scenario.
- I have the Edit/Employee view populated with a model from an Entity Framework entity (Employee)
- I post from Edit/Employee to the Save/Employee controller action. The Save/Employee action expect another type (EmployeeSave) which has Employee as property
This is the Edit/Employee method
public ActionResult Edit(EmployeesEdit command)
{
var employee = command.Execute();
if (employee != null)
{
return View(employee);
}
return View("Index");
}
This is the Save/Employee method
public ActionResult Save(EmployeesSave command)
{
var result = command.Execute();
if (result)
{
return View(command.Employee);
}
return View("Error");
}
This is the EmployeeSave class
public class EmployeesSave
{
public bool Execute()
{
// ... save the employee
return true;
}
//I want this prop populated by my model binder
public Employee Employee { get; set; }
}
The MVC DefaultModelBinder is able to resolve both Employee and EmployeeSave classes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能需要在此处使用
BindAttribute
。如果您的视图包含像这样命名的EmployeeSaveViewModel
和Employee
的属性(我编写了属性名称)那么,您的操作可能如下所示:
You might need to use
BindAttribute
here. If your view contains the properties of theEmployeeSaveViewModel
andEmployee
named like this (I made up property names)Then, your action could look like this:
您可以通过将编辑后的数据传递回处理 HttpPost 的编辑操作来解决此问题。在内部创建 EmployeeSave 对象并将其 Employee 属性分配给您的 Edit 操作返回的 Employee 值。通过传递 EmployeeSave 对象来调用 Save 操作。
另一种方法是使用 EmployeeSave 而不是 Employee 作为模型。
You could resolve it by passing the edited data back to Edit action that handles HttpPost. Inside create EmployeeSave object and assign its Employee property the value of Employee returned to yout Edit action. Call Save action by passing EmployeeSave object.
Another method would be to use EmployeeSave instead of Employee as your model.