Reputation: 541
Is it possible to put 2 models in one view? My page is working fine with one model, however when i attempt to add the other model line below my code decides to start having a number of errors:
@model ProjectShop.Models.Delivery
My code that works before i add the line above is shown below:
@model ProjectShop.Models.Products
@{
ViewBag.Title = "Products";
Layout = "~/Views/Shared/_ProductLayout.cshtml";
}
<p>@Html.DisplayFor(model => model.productname) </p>
What would be the method of having 2 models in one view enabling me to call data from two sources?
Edit:
This is a new class which will act as the view model for html page but i assume its not right at all:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ProjectShop.Models;
namespace ProjectShop.ViewModels
{
public class ProductDelivTimes
{
public Models.Products;
public Models.Delivery;
}
}
Edit:
public class ProductDelivTimes
{
public Models.Products ProductModel;
public Models.Delivery DeliveryModel;
}
In my html file:
@model IEnumerable<ProjectShop.ViewModels.ProductDelivTimes>
Edit:
@model IEnumerable<ProjectShop.ViewModels.PerformanceTimes>
@{
Layout = "~/Views/Shared/_Layout.cshtml";
var grid = new WebGrid(Model, rowsPerPage: 5, defaultSort: "Name");
ViewBag.Created = TempData["ProductCreated"];
ViewBag.Created = TempData["ProductDeleted"];
}
@grid.GetHtml(
tableStyle: "grid",
headerStyle: "gridhead",
rowStyle: "gridRow",
alternatingRowStyle: "gridRow",
mode: WebGridPagerModes.All,
columns: grid.Columns(
grid.Column("Image", format: @<text><img src="@item.image" alt="" width="84px" height="128px"/></text>, style: "Image"),
grid.Column("Products", format: @<text>@Html.Raw(item.Products.name.Substring(0, item.Products.name.IndexOf(".") + 1))</text>, style: "Products")
))
Upvotes: 0
Views: 279
Reputation: 31630
If you want to have multiple Domain entities as a part of a view, consider creating a View Model that combines two data source models
Something like (just pseudocode):
ProductDeliveryViewModel
{
// ProductModel
// DeliveryModel
}
So you would have
@model ProjectShop.Models.ProductDeliveryViewModel
@Html.DisplayFor (model=> model.ProductModel.Property)
@Html.DisplayFor (model=> model.DeliveryModel.Property)
Upvotes: 5
Reputation: 1433
In the past I have acheived this by using a third 'container' model.
public class MainModel
{
public ProductModel productModel {get;set;}
public DeliveryModel deliveryModel {get;set;}
}
Upvotes: 1
Reputation: 1381
The teams I've been on would use a ViewModel class to wrap both business objects into one object that can be used by the view. It can be as simple as having a property for each object.
Upvotes: 2
Reputation: 28802
Maybe write a wrapper model that contains the two data source models and decides which one to get the data from, when needed?
Upvotes: 2