Asp.net mvc ASP.Net MVC、ViewPage<;动态>;和EditorFor/LabelFor

Asp.net mvc ASP.Net MVC、ViewPage<;动态>;和EditorFor/LabelFor,asp.net-mvc,dynamic,Asp.net Mvc,Dynamic,我正在使用Razer语法处理MVC3,不过我认为问题更一般 在控制器中,我有如下内容: ViewModel.User = New User(); // The model I want to display/edit ViewModel.SomeOtherProperty = someOtherValue; // Hense why need dynamic Return View(); <p> @Html.LabelFor(x => x.User.Name @Html.Ed

我正在使用Razer语法处理MVC3,不过我认为问题更一般

在控制器中,我有如下内容:

ViewModel.User = New User(); // The model I want to display/edit
ViewModel.SomeOtherProperty = someOtherValue; // Hense why need dynamic
Return View();
<p>
@Html.LabelFor(x => x.User.Name
@Html.EditorFor(x => x.User.Name
</p>
我的视图继承自System.Web.Mvc.ViewPage

但如果我试着做以下事情:

ViewModel.User = New User(); // The model I want to display/edit
ViewModel.SomeOtherProperty = someOtherValue; // Hense why need dynamic
Return View();
<p>
@Html.LabelFor(x => x.User.Name
@Html.EditorFor(x => x.User.Name
</p>

@LabelFor(x=>x.User.Name
@EditorFor(x=>x.User.Name)

我得到错误:“表达式树可能不包含动态操作”

但是,ViewPage的使用似乎相当普遍,EditorFor/LabelFor也是如此。因此,如果没有办法做到这一点,我会感到惊讶-请欣赏任何指针。

不要使用
ViewPage
。我建议您使用视图模型,并强烈键入此视图模型的视图:

var model = new MyViewModel
{
    User = new User
    {
        Name = "foo"
    },
    SomeOtherProperty = "bar"
};
return View(model);
然后在
ViewPage
中强烈键入视图,然后:

@Html.LabelFor(x => x.User.Name)
@Html.EditorFor(x => x.User.Name)
<div>@Model.SomeOtherProperty</div>
@Html.LabelFor(x=>x.User.Name)
@EditorFor(x=>x.User.Name)
@Model.SomeOtherProperty

似乎表达式树=>不能包含任何动态变量

不幸的是,当您在TModel中使用动力学时,它就是这种情况

public static MvcHtmlString TextBoxFor<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func> expression
)
公共静态MvcHtmlString TextBoxFor( 这个HtmlHelper HtmlHelper, 表情 )
要键入视图,请在cshtml文件顶部添加@model Namespace.Classname声明。