ASP.Net MVC, ViewPage <Dynamic> and EditorFor / LabelFor

I play with MVC3 using Razer syntax, although I think the problem is more general.

In the controller, I have something like:

 ViewModel.User = New User(); // The model I want to display/edit ViewModel.SomeOtherProperty = someOtherValue; // Hense why need dynamic Return View(); 

My view inherits from System.Web.Mvc.ViewPage

But if I try to do something like:

 <p> @Html.LabelFor(x => x.User.Name @Html.EditorFor(x => x.User.Name </p> 

I get the error: "The expression tree may not contain a dynamic operation"

However, using ViewPage seems pretty common, as does EditorFor / LabelFor. Therefore, I would be surprised if there was no way to do this - appreciate any pointers.

+6
source share
2 answers

It seems that the expression trees => http://msdn.microsoft.com/en-us/library/bb397951.aspx should not contain dynamic variables.

Unfortunately, this applies to TModel when you use dynamics.

 public static MvcHtmlString TextBoxFor<TModel, TProperty>( this HtmlHelper<TModel> htmlHelper, Expression<Func> expression ) 
0
source

Do not use ViewPage<Dynamic> . I would recommend you use a view model and strongly print your view of this view model:

 var model = new MyViewModel { User = new User { Name = "foo" }, SomeOtherProperty = "bar" }; return View(model); 

and then strictly enter your view in the ViewPage<MyViewModel> and:

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

All Articles