如何使部分视图在不同的视图模型中可重用(asp.net mvc 2)?

3
我创建了一个部分视图,希望能在网站的不同页面上重复使用。
目前,我为每个网页创建一个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 mvc 2中使用部分视图,以便它可以在任何网页上重复使用并接受任何视图模型?
在某个地方,我觉得我可能错过了一些显而易见的东西...
1个回答

2

创建一个与价格部分特定的视图模型。将该视图模型包含在调用页面使用的页面级视图模型中。然后在调用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); %>

谢谢您。我需要仔细思考,但我现在理解了您建议的方法。让我试一下... - Alex P

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接