views:

592

answers:

2

First of all, I'm really new to the MVC Asp.Net ideology.

I would like to know how can I create two objects (model) into one view ?

because if I look at the view header it's inherit from one model :

\<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

So, if, for example, I want to create in the same view (Aspx page) an MyObjectA and an object MyObjectB, what's the best way to handle that ?

I hope I've been clear ...

+3  A: 

If you have a model object Person and another lets say Comment and then in the same view you would like to display a persons details and comments added to that person you may want to create an intermediate object sometimes referred to as a 'data transfer object' or 'view object'. So, i create a simple class:

public class PersonDetailDTO
{
    public Person PersonDetail {get; set;}
    public IList<Comment> Comments {get; set;}
}

.. now i can return the result of my action as type PersonDetailDTO instead of say Person. Then the view is strongly typed to PersonDetailDTO also, making it easy for me to access the PersonDetail data and Comments collection.

For example, i use a view object like this for one of my partial views:

        public class AnnouncementsPartialViewData
        {
            public IList<Announcement> Announcements { get; set; }
            public object MonthlyPlannerRouteVals { get; set; }
            public object PreSchoolRouteVals { get; set; }
            public object ElementaryRouteVals { get; set; }
        }

.. and the partial view header looks like this:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<KsisOnline.Web.Controllers.HomeController.IndexViewData.AnnouncementsPartialViewData>" %>

.. and so i can access the typed data from that view class in the view easily like so:

<% if (Model.Announcements.Count == 0)
cottsak
+3  A: 

If by 'creating' you mean 'passing' two objects from a controller to a view, you should create a new class that would contain the two objects and pass it from the controller to the view:

public class MyModel
{
  public MyObjectA ObjectA { get; set; }
  public MyObjectB ObjectB { get; set; }
}

The View definition would then look like this:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MyModel>" %>

In the controller, you would create the object like

...(in controller action)
return new MyModel { ObjectA = new MyObjectA(), ObjectB = new MyObjectB() };

From the view, you would access the objects like

var myObjectA = Model.ObjectA;
gius