Not That Obvious In MVC

I am working on converting some ASP.NET WebForms pages into MVC Views and there are a couple of things I have run across in MasterPages that are not obvious in the beginning. With ASP.NET WebForms if you wanted dynamic content in your MasterPage one way to do it is to have the code behind of the MasterPage insert it, which means that your Page either need to tell the Master Page what to insert or the Master Page need to figure it out. Take this for example:
    <meta name="Description" content="" id="metaDescription" runat="server" />
Here I am trying to add a meta description the head of the HTML so that the search engines know what this page is about. What I was doing is have the page check the type of the master class on the pages OnInit event and if it was the right master class, find the public property in the MasterPage that would set the MetaDescription. When the MasterPage pre-rendered it would insert the value of that property into the content attribute of the server side control. With ASP.NET MVC you don't have code behind. It was not obvious to me (however it makes sense now) that the MasterPage has access to all the ViewData, so in MVC the above looks like this:
    <meta name="Description" content="<%=ViewData["MetaDescription"]%>"/>
All I have to do in this case is set the MetaDescription of the ViewData in the controller and it will get filled in on this MasterPage. It is not obvious also that if I don't set the ViewData for the MetaDescription then the content attribute gets an String.Empty. You might say: "That is how it should work?" Well it should, unless you consider that ViewData holds objects and has an arbitrary number of entries. So referencing an unset entry should give a KeyNotFoundException or maybe a NullReferenceException, however this has been cleanly handled in ASP.NET MVC. Which means that as I program the View, I don't need to worry about all the controllers that use this view setting the MetaDescription. If they set it great I will use it, otherwise it is blank. {6230289B-5BEE-409e-932A-2F01FA407A92}


  1. You should look at strongly typed view models too. I try to rarely use the indexer the way you describe so that I get compile time errors when something changes.


Post a Comment

Popular posts from this blog

Simple WP7 Mango App for Background Tasks, Toast, and Tiles: Code Explanation

Yet once more into the breech (of altered programming logic)

How to convert SVG data to a Png Image file Using InkScape