开发者

How can I make a partial view re-usable across different viewmodels (asp.net mvc 2)?

I have created a partial view that I'd like to be able to re-use on different pages of my website.

Currently, for each webpage I create a ViewModel that collates all the information I would like to show and then I send it to the view which compromises of 3 separate partial views. Here is a simplified example:

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
    }

In my webpage each partial view inherits from the same view model which allows me to strongly type each partial view:

Inherits="System.Web.Mvc.ViewUserControl<DomainModel.Entities.MyViewModel>

My issue is that I would like to use one of my partial views ('Prices.ascx') in other webpages as it is quite generic. However, because it inherits from DomainModel.Entities.MyViewModel I get an error if I try to pass another view model e.g. CheckOutViewModel.

I am not sure how I can get around this i开发者_JS百科ssue? How do I use a partial view in asp.net mvc 2 so that it can be re-used on any webpage and accept any view model?

Somewhere along the way I feel that I have missed something obvious...


Create a view model specific to the Prices partial. Include that view model within the Page level view model used by the calling pages. Then when calling the RenderPartial, pass the appropriate part of the model to the partial.

public MyViewModel GetModelData()
    {
        ModelData modelData = new ModelData();
        modelData.employees = GetEmployees();
        modelData.products = GetProducts();
        modelData.MyPricesViewModel = GetPrices();   <-- this should be a view model
        return modelData
    }

Edit your partial view to only inherit from the model that is specific to it's needs.

Inherits="System.Web.Mvc.ViewUserControl<DomainModel.Entities.MyPricesViewModel>

Within your view page you would then call:

<% Html.RenderPartial("Prices", Model.MyPricesViewModel); %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜