我想将模型传递给布局和视图,其中包含通用对象类型。我有以下内容;
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);
}
所以在这个例子中,我传递的baseModel布局包含对象类型ProductType1。在我的布局顶部,我有
@model Project1.Models.BaseModel
在视图中,如何将ModelObject转换为ProductType1,例如,我可以引用类似ProductType1.Name的模型。
答案 0 :(得分:4)
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>