2011-01-28 77 views
0

我想將一個委託或命令對象作爲參數發送給EditorFor以及模型對象。我可以使用viewdata發送它,但我非常喜歡它強類型。有沒有合理的方法來做到這一點?MVC EditorFor用複合模型類型?

這大概想什麼,我能在編輯模板做:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Pair<MyModelType, TheDelegate>>" %> 

但我怎麼能我的委託添加到這樣的表達式呢?

<%= Html.EditorFor(m => m.MyModelTypeField, "ThatEditor") %> 

回答

1

除非您修改視圖模型並讓控制器傳遞必要的信息,否則不能以強類型的方式進行此操作。所以

public class MyModelTypeWithDelegate 
{ 
    public MyModelType MyModelType { get; set; } 
    public TheDelegate MyModelTypeDelegate { get; set; } 
} 

public class MyViewModel 
{ 
    public MyModelTypeWithDelegate MyModelTypeWithDelegate { get; set; } 
} 

然後:

<%= Html.EditorFor(m => m.MyModelTypeWithDelegate, "ThatEditor") %> 

另一種可能是把它作爲額外的可視數據,但它不會被強類型:

<%= Html.EditorFor(m => m.MyModelTypeField, "ThatEditor", new { TheDelegate = someDelegate }) %> 

,然後你的編輯模板中:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyModelType>" %> 
<% 
    var del = (TheDelegate)ViewData["TheDelegate"]; 
%> 
+0

我一直希望能夠創建m => m.MyModelTypeField表達式中另一個類型的新實例。謝謝你讓我知道! – 2011-01-28 11:14:15