我已经创建了一个部分视图,我希望能够在我的网站的不同页面上重复使用。
目前,对于每个网页,我创建了一个ViewModel,它整理了我想要显示的所有信息,然后我将其发送到3个单独的部分视图的折衷视图。下面是一个简化的示例:
public ActionResult Index()
{
MyViewModel m = new MyViewModel();
MyViewModel modelData = m.GetModelData();
return View(modelData);
}
public MyViewModel GetModelData()
{
ModelData modelData = new ModelData();
modelData.employees = GetEmployees();
modelData.products = GetProducts();
modelData.prices = GetPrices();
return modelData
}在我的网页中,每个局部视图都继承自相同的视图模型,这允许我强类型每个局部视图:
Inherits="System.Web.Mvc.ViewUserControl<DomainModel.Entities.MyViewModel>我的问题是,我想在其他网页中使用我的一个局部视图('Prices.ascx'),因为它非常通用。但是,因为它继承自DomainModel.Entities.MyViewModel,所以如果我试图传递另一个视图模型,例如CheckOutViewModel,我会得到一个错误。
我不知道如何才能解决这个问题?如何在asp.net MVC2中使用局部视图,以便可以在任何网页上重用它并接受任何视图模型?
一路走来,我觉得我遗漏了一些明显的东西...
发布于 2010-10-06 19:31:42
创建特定于部分价格的视图模型。包括在调用页使用页面级视图模型中。然后,在调用RenderPartial时,将模型的适当部分传递给部分。
public MyViewModel GetModelData()
{
ModelData modelData = new ModelData();
modelData.employees = GetEmployees();
modelData.products = GetProducts();
modelData.MyPricesViewModel = GetPrices(); <-- this should be a view model
return modelData
}编辑您的局部视图,使其仅从特定于其需要的模型继承。
Inherits="System.Web.Mvc.ViewUserControl<DomainModel.Entities.MyPricesViewModel>然后,在视图页面中调用:
<% Html.RenderPartial("Prices", Model.MyPricesViewModel); %>https://stackoverflow.com/questions/3871037
复制相似问题