neildt
neildt

Reputation: 5352

How to pass generic property type of model to MVC view

I am wanting to pass a model to a layout and view, of which contains a generic object type. I have the following;

   public class BaseModel
   { 
       public int ProductId {get;set;}
       public Object ModelObject { get; set; } 
   }

   public class ProductType1 
   {
        public string Name {get;set;}
        public decimal Price {get;set;}
   }

   public class ProductType2
   {}

   public ActionResult Index()
   {
      BaseModel baseModel = new BaseModel(); 
      baseModel.ModelObject = new ProductType1();  
      return View("View1", "_MyLayOut", baseModel);
   } 

So in this example I am passing to the layout the baseModel which contains the object type ProductType1. At the top of my layout I have

@model Project1.Models.BaseModel

In the view, how do I cast the ModelObject to ProductType1, so for example I can reference the model like ProductType1.Name.

Upvotes: 1

Views: 1065

Answers (1)

Backs
Backs

Reputation: 24903

public class BaseModel<T>
{ 
    public int ProductId {get;set;}
    public T ModelObject { get; set; } 
}
// ...
BaseModel<ProductType1> baseModel = new BaseModel<ProductType1>(); 
// ...
@model Project1.Models.BaseModel<ProductType1>

Upvotes: 4

Related Questions