About the author

Morten Krogh-Jespersen is the founder of dotnamics - an IT company that develop products and consults in the programming field.

Dynamic data/controller in a masterpage in an ASP.NET MVC website

by Morten Krogh-Jespersen 13. juli 2010 03:28

A lot of web pages provide dynamic data on every page, this could for instance be an advertisement or a funny joke.

On the dotnamics website, there's a dynamic header on every page (except blog pages), which displays a customer reference, a product reference and so on.

I've seen some posts on how to do it, but almost everybody suggest building a base controller - BUT I don't like that idea. Building a base controller might be a good idea, but I think a controller should be encapsulated, and only solve the problem at hand. If you put to much information in a base-controller, you remove the purpose of the controller, imho.

I used the RenderAction html helper to solve the problem.

1: Create a controller, I called mine MasterPageController:

namespace dotnamics2010.Controllers
{
    public class MasterPageController : Controller
    {
        public ActionResult HeaderContent()
        {
            Models.ViewModels.MasterPage.HeaderContent headerContent = new Models.ViewModels.MasterPage.HeaderContent();
            headerContent.InPlaceShuffle();
            return View(headerContent);
        }
    }
}

What this does is, it calls a viewmodel, that generates different headers. I then shuffle the items, before i send the data to the view.

2: add a View:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dotnamics2010.Models.ViewModels.MasterPage.HeaderContent>" %>

<div id="headercontent">
    <div class="items">
        <%
            foreach (dotnamics2010.Models.ViewModels.MasterPage.IHeaderContent content in Model)
            {
                %>
                    <div>
                        <% Html.RenderPartial(content.GetType().Name, content); %>
                    </div>
                <%
            }
            %>
    </div>
 </div>

3: Finally, include in masterpage like this:

                <div id="header_content">
                    <% Html.RenderAction("HeaderContent", "MasterPage"); %>
                </div>

I think this is the perfect solution.

Tags: , ,

ASP.NET | ASP.NET MVC | Masterpage