Search code examples
asp.net-mvc-2command-patterndefaultmodelbinder

How to bind a model property with DefaultModelBinder - ASP.NET MVC2


I have the following scenario.

  1. I have the Edit/Employee view populated with a model from an Entity Framework entity (Employee)
  2. 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.


Solution

  • 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);
    }