Is there a way to get a reference for the ViewPage that contains a parital view from the partial view ??
Not 100% but I don't think this is possible. What specifically do you want to reference in the ViewPage from the Partial? Couldn't you just share a Model between the ViewPage and ViewUserControl?
It seems there is no standard property for this so you should pass ViewPage object to partial view yourself:
<% Html.RenderPartial("partial_view_name", this); %>
The absolute answer: NO
You need to use ViewData or Model to share it.
My solution was a baseclass for any models used by partial controls. It's useful for the times when you need to specify a model but want the partial view to have access to certain things from the containing View's model.
Note: this solution will support a hierarchy of partial views automatically.
Usage:
When you call RenderPartial supply the Model (for the view). Personally I prefer this pattern, which is to create a view in place on the page consisting of whatever the patial view might need from the parent model.
I create a ProductListModel
from the current model, which makes the parent model available easily to the partial view.
<% Html.RenderPartial("ProductList", new ProductListModel(Model)
{ Products = Model.FilterProducts(category) }); %>
In the partial control itself you specify the ProductListModel
as a strongly typed view.
<%@ Control Language="C#" CodeBehind="ProductList.ascx.cs"
Inherits="System.Web.Mvc.ViewUserControl<ProductListModel>" %>
Model class for the partial view
Note: I'm using IShoppingCartModel
to specify the model to avoid coupling from the partial back to the containing view.
public class ProductListModel : ShoppingCartUserControlModel
{
public ProductListModel(IShoppingCartModel parentModel)
: base(parentModel)
{
}
// model data
public IEnumerable<Product> Products { get; set; }
}
Baseclasses:
namespace RR_MVC.Models
{
/// <summary>
/// Generic model for user controls that exposes 'ParentModel' to the model of the ViewUserControl
/// </summary>
/// <typeparam name="T"></typeparam>
public class ViewUserControlModel<T>
{
public ViewUserControlModel(T parentModel)
: base()
{
ParentModel = parentModel;
}
/// <summary>
/// Reference to parent model
/// </summary>
public T ParentModel { get; private set; }
}
/// <summary>
/// Specific model for a ViewUserControl used in the 'store' area of the MVC project
/// Exposes a 'ShoppingCart' property to the user control that is controlled by the
/// parent view's model
/// </summary>
public class ShoppingCartUserControlModel : ViewUserControlModel<IShoppingCartModel>
{
public ShoppingCartUserControlModel(IShoppingCartModel parentModel) : base(parentModel)
{
}
/// <shes reummary>
/// Get shopping cart from parent page model.
/// This is a convenience helper property which justifies the creation of this class!
/// </summary>
public ShoppingCart ShoppingCart
{
get
{
return ParentModel.ShoppingCart;
}
}
}
}