我有以下情况。
这是编辑/员工方法
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类。
答案 0 :(得分:1)
您可能需要在此处使用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);
}
答案 1 :(得分:0)
您可以通过将已编辑的数据传递回处理HttpPost的编辑操作来解决此问题。在里面创建EmployeeSave对象并为其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作为模型。