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.

有帮助吗?

解决方案

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

其他提示

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.

[HttpGet]
public ActionResult Edit()
{
    return View();
}

[HttpPost]
public ActionResult Edit(Employee employee)
{
    EmployeeSave employeeSave = new EmployeeSave { Employee = employee };

    return View("Save", employeeSave);
}

Another method would be to use EmployeeSave instead of Employee as your model.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top