6

I'm playing with MVC3 using the Razer syntax, though I believe the problem to be 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: "An expression tree may not contain a dynamic operation"

However, the use of ViewPage seems quite common, as are EditorFor/LabelFor. Therefore I'd be surprised if there's not a way to do this - appreciate any pointers.

2 Answers 2

3

Don't use ViewPage<Dynamic>. I would recommend you using a view model and strongly type your view to this view model:

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

and then strongly type your view to ViewPage<MyViewModel> and:

@Html.LabelFor(x => x.User.Name)
@Html.EditorFor(x => x.User.Name)
<div>@Model.SomeOtherProperty</div>
Sign up to request clarification or add additional context in comments.

1 Comment

In order to type your view, add a @model Namespace.Classname declaration to the top of your cshtml file.
0

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

Unfortunately this is the case for TModel when you use dynamics in it.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.