Reputation: 35
I have a MVC2 project with a ViewModelBase. I have a PartialView called by the masterPage :
<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage<MyProject.Web.FrontOffice.Models.ViewModels.ViewModelBase>" %>
<% Html.RenderPartial("~/Views/Shared/Controls/Header.ascx"); %>
This PartialView also call a PartialView :
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyProject.Web.FrontOffice.Models.ViewModels.ViewModelBase>" %>
<% Html.RenderPartial("~/Views/Shared/Controls/BannerFront.ascx"); %>
This last PartialView needs a ViewModelBannerFront that inherits ViewModelBase :
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Curioos.Web.FrontOffice.Models.ViewModels.ViewModelBannerFront>" %>
I thought with the inheritance, there will be no problem, I set the ViewModelBannerFront in the controller :
public ActionResult Index(string username)
{
//other stuff
ViewModelBannerFront vmbf = new ViewModelBannerFront();
return View(vmbf);
}
This action calls a view which is contained in the masterpage (which contains header partialview etc...).
I have a type error, could you help me please? How can I pass a ViewModelBannerFront in my last PartialView? Thank you in advance
Upvotes: 1
Views: 1880
Reputation: 22485
Pat,
Rather than run a renderpartial, try doing the following and it should work:
// assuming that your banner controller is called BannerFrontController
<%Html.RenderAction("Index", "BannerFront"); %>
the reason that <% Html.RenderPartial("~/Views/Shared/Controls/BannerFront.ascx"); %>
doesn't work is due to the fact that the model is passed directly from the parent view model (i.e. MyProject.Web.FrontOffice.Models.ViewModels.ViewModelBase
) when being invoked as a partialview. This means that you don't run the code via the controller, instead, invoking the partial directly and being populated by the parent view model. Given that the view-type required (in the partialview) is ViewModelBannerFront
, herein lies the issue.
The other way to attack the problem is to compose your viewmodel, so as to contain both the ViewModelBase and the ViewModelBannerFront. then, simply call the partial view along the lines of:
// no need to call entire path as views are in shared folder
<% Html.RenderPartial("Header", Model.ViewModelBase); %>
<% Html.RenderPartial("BannerFront", Model.ViewModelBannerFront); %>
etc, etc.. hope this makes sense.
see this link to get a closer feel for renderpartial vs renderaction:
http://devlicio.us/blogs/derik_whittaker/archive/2008/11/24/renderpartial-vs-renderaction.aspx
Upvotes: 2