Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass multiple objects to ViewPage in ASP.NET MVC?

Tags:

asp.net-mvc

I think I know the answer, but I would like to bounce around some ideas.

I would like to pass several (in this instance 2) somewhat different pieces of data to a View. My initial thought is simply to wrap-up the various objects into a containing object and pass them along that way. Then from the View, I'd have something like

var objContainer = ViewData.Model;
var thisObject = objContainer.ThisObject;
var thatObject = objContainer.ThatObject;

and these could be used independently in the Master Page and View Page.

Is that the "best" way?

like image 862
oglester Avatar asked Oct 26 '08 18:10

oglester


People also ask

Can we bind multiple models to view?

We can Bind Multiple Models with the help of Json as well. We will retun JsonResult from action Method and on View through JQuery, we can parse the JSON data and Bind on View.

How many ways we can pass data from view to controller?

This blog will discuss four (4) common ways to pass data from the view to the controller: Passing by Typed Arguments. Request Object. Form Collections Object.


2 Answers

I find it useful to create additional classes dedicated that are to be presented to the Views. I keep them in a separate namespace called 'Core.Presentation' to keep things organized. Here is an example:

namespace Core.Presentation
{
    public class SearchPresentation
    {
        public IList<StateProvince> StateProvinces { get; set; }
        public IList<Country> Countries { get; set; }
        public IList<Gender> Genders { get; set; }
        public IList<AgeRange> AgeRanges { get; set; }
    }
}

Then I make sure that my View is a strongly typed view that uses the generic version of that presentation class:

public partial class Search : ViewPage<SearchPresentation>

That way in the View, I can use Intellisense and easily navigate through the items.

like image 139
David P Avatar answered Nov 15 '22 08:11

David P


Yes, the class that you specify as the model can be composed of other classes. However, why not just use the dictionary like so:

ViewData["foo"] = myFoo;
ViewData["bar"] = myBar;

I think this is preferable to defining the model as a container for otherwise unrelated objects, which to me has a funny smell.

like image 45
Tim Scott Avatar answered Nov 15 '22 08:11

Tim Scott