views:

31

answers:

3

I'm new to MVC2 in ASP.NET/C#, so please forgive me if I misunderstand something. I have code similar to this in my Controller:

var singleInstance = new Person("John");
ViewData["myInstance"] = singleInstance;
return View();

So in my view, Index.aspx, I want to be able to reference members in that object. For example, Person has a member called Name, which is set in the constructor. In the view I want to get Person.Name from what is stored in the ViewData object. Ex.:

<%= ViewData["myInstance"].name %>

That doesn't work. The only real workaround I've found is to do something like this:

<% var thePerson = ViewData["myInstance"];
print (or whatever the method is) thePerson.Name;
%>

Any help would be much appreciated... This was so much easier in PHP/Zend Framework... sigh

A: 

This should work, but what would be easier in this instance is to make use of the strongly typed views (good benefits in security and a little easier to modify the view with the model data). Then you can do this in your controller:

var singleInstance = new Person("John");
return View(singleInstance);

and this in your view:

<%= html.encode(model.name) %>

In your case, I do use the ViewData object in some instances, and what you have should work. Now, the IntelliSense in Visual Studio will not automatically bring up the properties of a specific ViewData object because you can pass 'anything' in the ViewData. Unless in C#, you have to have this.

<%= ViewData["myInstance"].name; %>

Maybe a C# ASP.MVC'er can weight in on this one

'anything'- just in case there is some object that you can't pass in here

EDIT: To comment on the print or whatever line

You don't have to call any methods to print anything out, you just wrap the variable/object in the <%= %> tags. The html.Encode() method helps to prevent XSS attacks and other nasties in the wild.

Tommy
A: 

Have a look at this tutorial.

Really you should (as Tommy mentions) pass the model objects through to the View using the return View(foo). But if you must use ViewData (sometimes you need to), simply cast your object back to its original type in your View.

i.e.

 <%= (ViewData["myInstance"] as Person).name; %>

You need to cast because ViewData is just a dictionary with objects. Its not strongly-typed, which is why passing straight through to the View using the ActionResult is preferred in most cases.

RPM1984
A: 

Why don't you create a strongly typed view that accepts a "Person"?

In your Controller

var singleInstance = new Person("John"); 
ViewData.Model = singleInstance; 
return View(); 

In your (strongly typed) View

<%= Html.Encode (Model.name) %>
Syd