2011-08-11 77 views
0

我有以下場景。如何使用DefaultModelBinder綁定模型屬性 - ASP.NET MVC2

  1. 我已經填充了從實體框架實體(員工)
  2. 我從編輯/員工以保存/員工控制器動作後的模型編輯/僱員視圖。保存/僱員動作期望另一種類型的(EmployeeSave),其具有僱員作爲屬性

這是編輯/僱員方法

public ActionResult Edit(EmployeesEdit command) 
    { 
     var employee = command.Execute(); 
     if (employee != null) 
     { 
      return View(employee); 
     } 
     return View("Index"); 
    } 

這是保存/僱員方法

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

什麼是創建命令對象在你的例子中傳入行動方法? –

+0

@BlessYahu ASP.NET MVC默認模型綁定器 – abx78

回答

1

您可能需要在這裏使用BindAttribute。如果您的視圖包含名爲像這樣的EmployeeSaveViewModelEmployee的屬性(我做了屬性名稱)

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

如果我將EmployeesSave作爲模型,這可能是一個好方法。但正如您在Edit動作中看到的,我剛添加的模型是Employee。這是我在我看來: '' – abx78

+0

我相信這將是最好的方法。即使從DefaultModelBinder繼承,爲應用程序中的每個命令/操作編寫自定義模型聯編程序也沒有任何意義。將該命令作爲視圖模型注入更具有防錯性和節省時間的優點。 – abx78

0

您可以通過將編輯的數據傳遞迴處理HttpPost的編輯操作來解決它。在內部創建EmployeeSave對象並將其Employee屬性的值分配給您返回給您的編輯操作。通過傳遞EmployeeSave對象來調用保存操作。

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

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

    return View("Save", employeeSave); 
} 

另一種方法是使用EmployeeSave而不是Employee作爲您的模型。

+0

使用EmployeeSave來代替Employee會解決這個問題。但我想保持從命令中分離命令。所以讓視圖只與模型一起工作。也許它需要一個自定義活頁夾? – abx78

相關問題