I have the following scenario.
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.
You might need to use BindAttribute
here. If your view contains the properties of the EmployeeSaveViewModel
and Employee
named like this (I made up property names)
<input type="text" name="EmployeeSaveViewModel.Property1" />
<input type="text" name="EmployeeSaveViewModel.Employee.Name" />
<input type="text" name="EmployeeSaveViewModel.Employee.SomeProperty" />
Then, your action could look like this:
[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);
}