MVC EditorFor与复合模型类型?

时间:2011-01-28 08:42:33

标签: asp.net-mvc editorfor

我想将一个委托或一个命令对象作为参数发送给EditorFor以及模型对象。我可以使用viewdata发送它,但我非常喜欢强类型。有没有合理的方法呢?

这大致是我希望在编辑器模板中能够做到的事情:

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

但是我怎么能将我的委托添加到这样的表达式?

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

1 个答案:

答案 0 :(得分: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") %>

另一种可能性是将其作为附加的viewdata传递,但不会强类型:

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

然后在你的编辑器模板中:

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