views:

61

answers:

1

Lately when I've been building my asp.net mvc apps I tend to have a number of items that consistently need to be calculated, formatted and configured in my master pages. Some of these items include:

  • I like to attach specific classed to the body tag like WordPress does to help my CSS out. I usually attach the name of the action, controller, page template, etc.
  • I like to work with a custom IIdentity in my master pages. This IIdentity includes the users nice Display Name, UserID, UserName, etc.
  • etc... depending on the project

The way I've gone about accomplishing this has evolved as well. I started out by sending ViewData along with every action result to populate things in the master page. example->

// in the action
ViewData["BodyClasses"] = "index home default";
ViewData["UserData"] = userData;

return View();

// in the master page
<% UserData userData = (UserData)ViewData["UserData"] %>
...
<body class="<%= (string)ViewData["BodyClasses"] %>">

That was horrible. So I started putting some variables at the top of my master pages and populating them based on the objects we have to work with in the master page. example ->

<%@ Master Language="C#" Inherits="System.Web.MVC.ViewMasterPage" %>
<% string controller = ViewContext.RouteData.Values["controller"].ToString().ToLower();
   string action = ViewContext.RouteData.Values["action"].ToString().ToLower(); 
   CustomIdentity identity = (CustomIdentity)User.Identity %>

...

<body class="no-js <%= controller + " " + action %>">

That's better but I feel like there has to be an easier solution. I started playing around with creating a custom ViewMasterPage and adding some public properties. Is anyone else doing this with the master page or is there another solution to this that I'm completely missing?

+1  A: 

I've used just regular content placeholders for body tag id's and classes.

<body id="<asp:ContentPlaceHolder ID="BodyTagId" runat="server" />">

Then use it in the given page that references the master page:

<asp:Content ContentPlaceHolderID="BodyTagId" runat="server">about-page</asp:Content>
AndrewDotHay
I use the same method as the questioner but I guess this makes sense if you want your pages to be filled with wordy <asp:Content /> tags. ;)
jfar
I get paid by the character. ;)
AndrewDotHay
@jfar - Which one of the approaches do you use? And what are either your thoughts on the custom ViewMasterPage, worth it?
DM
@DM, I already said "I use the same method as the questioner". That means I use the same technique as you.
jfar
@jfar, I understand that you were referring to me. I showed 2 different options (1 using ViewData, 1 using inline code at the top of the master page). I was curious which one of those you typically use?
DM
@DM Both. Whichever is convenient or simple at the time.
jfar