How do I do the above? I’ve started using MVC and I’m having issues passing data around.
My specific problem is to do with a list of objects I have in my Model which I need to access in a View and iterate through.
Thanks in advance.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Let’s say your controller action looks something like
Now you want to pass your list to the view, say ‘List.aspx’. You do this by having the action return a ViewResult (ViewResult is a subclass of ActionResult). You can use the Controller’s View method to return a ViewResult like so:
To be able to access the list in a strongly-typed fashion in your view, it must derive from ViewPage, where T is the type of the data you are passing in. Thus, in the current case our view (in List.aspx.cs) would something like this:
The data passed into the view in this way is referred to as the ‘ViewData’. To access the data, you must go through the ViewData.Model properties on the ViewPage. Thus, to render the contents of the list you would write (in List.aspx)
Here, this.ViewData.Model has the type you specified the type parameter T in ViewPage, so in our case this.ViewData.Model has type List.
You can use a repeater for rendering stuff like this, but I wouldn’t recommend it. If you want to use something similar, check out the Grid module of the MvcContrib project on CodePlex.