ASP.NET MVC 2 DisplayFor ()

I am looking at a new version of ASP.NET MVC (see here for more details if you haven't seen it yet) and I have some pretty simple issues with displaying object content.

In my control, I have a type object Person

that I am passing to a view in ViewData.Model

. So far so good and I can retrieve the object in a view ready for display. What I don't understand is how I need to call the method Html.DisplayFor()

to get the data to display. 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 assign a different value to "p" which is already being used in parent or current scope to indicate something else

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

NB I must add that I am reading about this in my limited spare time, so it is possible that I have missed something fundamental.

TIA

+2


source to share


2 answers


Html.DisplayFor

can only be used when your view is strongly typed and it is working on the object that was passed to the view.

So, for your case, you must declare your view with type Person as its model type (for example something.something.View<Person>

) (sorry, I don't remember the exact names, but it should make sense), and then when called Html.DisplayFor(p => p)

, it p

will take on the value of the passed model (Person) in view.



Hope this made sense.

+6


source


p is already a variable name; and variable names must be unique throughout the current scope. Therefore displayFor (p => p) is not valid as you are declaring a new variable 'p'. So the compiler doesn't know whether to use your character p or a variable (p =>).

So just rename it to



<%= Html.DisplayFor(person => person) %>

      

+1


source







All Articles