187

I have a model similar to this:

public class SampleModel
{
     public Product Product { get; set; } 
}

And in my controller I get an exception trying to print out

@Html.TextBoxFor(p => p.Product.Name)

This is the error:

Exception: An expression tree may not contain a dynamic operation

If anyone can give me some clues on how to fix this I would really appreciate it!

Scott Weldon
  • 9,673
  • 6
  • 48
  • 67
femseks
  • 2,914
  • 3
  • 23
  • 20
  • 1
    Is this on MVC3 RC? Also can you show us what Product looks like? I was unable to reproduce it in MVC3 RC – bmancini Nov 11 '10 at 15:35

7 Answers7

322

It seems to me that you have an untyped view. By default, Razor views in MVC3 RC are typed as dynamic. However, lambdas do not support dynamic members. You have to strongly type your model. At the top of your view file add

@model SampleModel
marcind
  • 52,944
  • 13
  • 125
  • 111
109

A common error that is the cause of this is when you add

@Model SampleModel

at the top of the page instead of

@model SampleModel
abatishchev
  • 98,240
  • 88
  • 296
  • 433
felbus
  • 2,639
  • 2
  • 24
  • 30
9

In this link explain about @model, see a excerpt:

@model (lowercase "m") is a reserved keyword in Razor views to declare the model type at the top of your view. You have put the namespace too, e.g.: @model MyNamespace.Models.MyModel

Later in the file, you can reference the attribute you want with @Model.Attribute (uppercase "M").

Community
  • 1
  • 1
Charlestown
  • 131
  • 1
  • 4
  • 2
    This was my problem. If you're not watching carefully, Visual Studio tends to convert what you're typing into the capital "M". It's really irritating. – RobbieE Jan 24 '17 at 12:43
7

Before using (strongly type html helper into view) this line

@Html.TextBoxFor(p => p.Product.Name)

You should include your model into you page for making strongly type view.

@model SampleModel
Opal
  • 81,889
  • 28
  • 189
  • 210
Kuber
  • 85
  • 1
  • 4
7

Seems like your view is typed dynamic. Set the right type on the view and you'll see the error go away.

Esteban Araya
  • 29,284
  • 24
  • 107
  • 141
2

This error happened to me because I had @@model instead of @model... copy & paste error in my case. Changing to @model fixed it for me.

JosephDoggie
  • 1,514
  • 4
  • 27
  • 57
0

On vb.net you must write @ModelType.

Perry
  • 1,113
  • 2
  • 10
  • 22