我有以下场景:
- 我用实体框架实体(雇员)的模型填充了编辑/雇员视图
- 我从Edit/Employee发布到Save/Employee控制器动作。保存/雇员操作期望另一种类型(EmployeeSave),其雇员属性
这是Edit/Employee方法
public ActionResult Edit(EmployeesEdit command)
{
var employee = command.Execute();
if (employee != null)
{
return View(employee);
}
return View("Index");
}
这是保存/雇员方法
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类。
这里可能需要使用BindAttribute
。如果您的视图包含EmployeeSaveViewModel
和Employee
的属性,命名如下(我自创的属性名称)
<input type="text" name="EmployeeSaveViewModel.Property1" />
<input type="text" name="EmployeeSaveViewModel.Employee.Name" />
<input type="text" name="EmployeeSaveViewModel.Employee.SomeProperty" />
然后,你的动作看起来像这样:
[HttpPost]
public ActionResult Save([Bind(Prefix="EmployeeSaveViewModel")]
EmployeeSaveViewModel vm)
{
if(ModelState.IsValid)
{
// do something fancy
}
// go back to Edit to correct errors
return View("Edit", vm);
}
您可以通过将编辑过的数据传递回处理HttpPost的Edit操作来解决这个问题。在内部创建EmployeeSave对象,并将返回给Edit操作的Employee的值分配给它的Employee属性。通过传递EmployeeSave对象调用Save操作。
[HttpGet]
public ActionResult Edit()
{
return View();
}
[HttpPost]
public ActionResult Edit(Employee employee)
{
EmployeeSave employeeSave = new EmployeeSave { Employee = employee };
return View("Save", employeeSave);
}
另一个方法是使用EmployeeSave代替Employee作为你的模型。