Saturday, September 4, 2010

ASP.NET MVC: Passing Data to Master Page without using ViewData

I've been working with MVC for a while now and my most common problem is when I want to put a Dynamic content on my Master Page depending on the Page that is being displayed. The most common thing to do here is that you don't want to put that Control/PartialView (.ascx) in your MasterPage instead you will create a PartialView and call it in each page that you want to place it with, and unfortunatelly, those pages are all of your pages that are using the MasterPage. So you have to place that control in all of your pages.

This kind of approach is already a very good approach since you will only need to change one PartialView page and this will reflect all of the other Pages that is using that PartialView Page.

Now I've been thinking, what if I can put that in the masterpage so that I can only include it once and only in the masterpage. After surfing around the internet. I found this post in StackOverflow about passing a strongly typed data to the masterpage.

I will try to show here the implementation that I made.

Create a BaseModel for your MasterPage.

First thing is to create a BaseModel class that will be inherited with your MasterPage and this will also be inherited to all of your Pages that is strongly-typed.

public class BaseModel
{
public string ProductIdRelations { get; set; }
}
You should inherit this in your MasterPage views

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage<Namespace.Models.BaseModel>" %>

You should access the Properties of your BaseModel by calling

<%=Model.RelatedProductId %>

Inherit BaseModel to all ViewModels of the pages.

You have to inherit your BaseModel to all of your ViewModels except for those PartialViews.

public class ProductViewModel : BaseModel
{
public ProductModel Product { get; set; }
}

public class ProductModel
{
public string ProductId { get; set; }
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public string ProductImage { get; set; }
}

Now in your Controller,

public class ProductController : Controller
{
ProductRepository prodRepository = new ProductRepository();

public ActionResult Product(int id)
{
ProductModel productModel = prodRepository.GetProduct(id);
ProductViewModel productViewModel = new ProductViewModel();
// you can set here the RelatedProductId of your BaseModel
productViewModel.ProductIdRelations = productModel.ProductId;

return View(productViewModel);
}
}

The View of my Product is inherting the ProductViewModel class

<%@ Page Title="Products" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<NameSpace.Models.ProductViewModel>" %>


In my next post, I will try to enhance this method by injecting IViewDataFactory as discussed in here

No comments:

Post a Comment