I'm looking at the new version of ASP.NET MVC (see here for more details if you haven't seen it already) and I'm having some pretty basic trouble displaying the content of an object.

In my control I have an object of type "Person", which I am passing to the view in ViewData.Model. All is well so far, and I can extact the object in the view ready for display. What I don't get, though, is how I need to call the Html.DisplayFor() method in order to get the data to screen. I've tried the following...

    MVC2test.Models.Person p = ViewData.Model as MVC2test.Models.Person;
// snip
<%= Html.DisplayFor(p => p) %>

but I get the following message:

CS0136: A local variable named 'p' cannot be declared in this scope because it would give a different meaning to 'p', which is already used in a 'parent or current' scope to denote something else

I know this is not what I should be doing - I know that redefining a variable will producte this error, but I don't know how to access the object from the controller. So my question is, how do I pass the object to the view in order to display its properties?

(I should add that I am reading up on this in my limited spare time, so it is entirely possible I have missed something fundamental)


+1  A: 

p is already a variable name; and variable names have to be unique throughout the current scope. Therefore displayFor(p=>p) is not valid, as you're declaring a new variable 'p' there. That way the compiler doesn't know wether to use your Person p, or the (p =>) variable.

So just rename it to

<%= Html.DisplayFor(person => person) %>
Jan Jongboom
Thanks for the answer, but what I'm really after is how to access the object I have passed in to the view in ViewData.Model within the DisplayFor method. Redeclaring as a new variable doesn't achieve that goal.
+4  A: 

Html.DisplayFor can be used only when your View is strongly-typed, and it works on the object that was passed to the View.

So, for your case, you must declare your View with the type Person as its Model type, (e.g. something.something.View<Person>) (sorry, I don't remember the exact names, but this should make sense), and then when calling Html.DisplayFor(p => p), p would take the value of the passed model (Person) value into the view.

Hope that made sense.

Thanks for that. I'll give it a whirl tomorrow when I'm back in the office. :)
Excellent answer. Thanks, it worked (but you already knew that, didn't you? ;) )
Actually, I didn't. Well, not entirely anyway.I'm currently in the process of learning ASP.NET MVC 1.0, but I've read some articles on 2.0, and remembered reading something on Html.DisplayFor; some Googling helped with the actual syntax and whatnot :)