Asp.Net MVC - View & # 8594; Creation of 2 objects
First of all, I am really new to the MVC Asp.Net ideology.
I would like to know how to create two objects (models) in one view?
because if I look at the view header it inherits 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) MyObjectA and an object MyObjectB, what's the best way to handle this?
I hope I get it ...
a source to share
If you have a model object Person
and another one Comment
and then in the same view you want to display the person's details and comments added to that person, you might 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 a type PersonDetailDTO
rather than say Person
. The view is then also strictly typed in PersonDetailDTO
, making it easier for me to access PersonDetail data and comment collections.
For example, I am using 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 title of the partial view looks like this:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<KsisOnline.Web.Controllers.HomeController.IndexViewData.AnnouncementsPartialViewData>" %>
.. and therefore I can easily access typed data from this view class in the form:
<% if (Model.Announcements.Count == 0)
a source to share
If "create" means "pass" two objects from controller to view, you must create a new class that will contain two objects and pass it from controller to view:
public class MyModel
{
public MyObjectA ObjectA { get; set; }
public MyObjectB ObjectB { get; set; }
}
The view definition will look like this:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MyModel>" %>
In the controller, you have to create an object like
...(in controller action)
return new MyModel { ObjectA = new MyObjectA(), ObjectB = new MyObjectB() };
In the view, you will be able to access objects like
var myObjectA = Model.ObjectA;
a source to share