开发者

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 Employ开发者_如何学JAVAeesSave
{
    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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜