ASP.NET MVC 2.0 ViewData – Best practices, Abolish ViewData


ASP.NET MVC is great! I really dig the MVC design pattern.There is something about MVC that makes the developer feel like a developer again.

However, it hasn’t been a smooth road getting up to speed with best practices, lots of articles don’t explain what is the correct way to do things. This is how it is…. accept it. Coming from years of ASP.NET web forms development I will tell you there is a bit of a learning curve with this web application development paradigm shift.

There is a lot to get your head around: .Net routing, models, views, controllers and validation. Also, you better brush up on your javascript! The 90′s are back. jQuery is your new best friend …. To the point ….

I wanted to talk specifically about using ViewData. Most importantly on not using ViewData!
ViewData is a dictionary object that allows you to easily pass data to your views from a controller:

public ActionResult Index()
{
	Object businessObject = new Object();
        List<Object> listOfBusinessObjects = new List<object>();
        Object businessObject2 = new Object();

        ViewData["Message"] = "Welcome to ASP.NET MVC!";
        ViewData["BusinessObject"] = businessObject;
        ViewData["ListOfBusinessObjects"] = listOfBusinessObjects;
        ViewData["BusinessObject1"] = businessObject2;

        return View();
}

In the view you do something similar to this:

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <% 
        Object businessObject = (Object)ViewData["BusinessObject"];
        List<Object> listOfBusinessObjects = (List<Object>)ViewData["ListOfBusinessObjects"];
        Object businessObject1 = (Object)ViewData["BusinessObject1"];   
    %>
    <h2><%: ViewData["Message"] %></h2>
    <p>
        To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
    </p>
</asp:Content>

Seems innocent, right? Well there are a few issues with using ViewData.

  1. It isn’t strongly typed
  2. Gets harder to do validation (roll your own)
  3. Need to know the types of each ViewData dictionary entry (ViewData["sometype"], what type is this…????) to cast
  4. Puts more code into the view, less readable because of the casts
  5. All around error prone

Imagine a real world scenario with web services, custom objects, and other complexities. Creating a N amount ViewData entries. Each layer of MVC project worked on by different developers.

AHH, Hey Bob… Can you give me details of the ViewData from your controller and the type of each Object inserted into ViewData?

“Neil, you are such a n00b, trace through my controller and find out for yourself!”

Neil should tell Bob to F!@K himself. He could have created the controller himself. Now he has to go through all of Bob’s code to find out what ViewData entries exist and what type to cast them.

Solution to all this nonsense is: View Model Classes and Strongly Typed Views. Lets do it:

Here is the View Model class:

namespace MvcApplication1.Models
{
    public class IndexViewModel
    {
        public Object BusinessObject { get; private set; }
        public List<Object> ListOfBusinessObjects { get; private set; }
        public Object BusinessObject2 { get; private set; }
        public string Message { get; set; }

        public IndexViewModel(Object businessObject, List<Object> listofBusinessObjects,
            Object businessObject2, string message)
        {
            this.BusinessObject = businessObject;
            this.ListOfBusinessObjects = listofBusinessObjects;
            this.BusinessObject2 = businessObject2;
            this.Message = message;
        }
    }
}

Note: there is lots of discussion and opinions on where to stick View Model classes. I personally keep them in Model folder. Some say they belong
in the controller, because they are created for the controller and not part of the true model layer. To Each a Zone. Hehe.

The IndexViewModel Contains all the information we need for the View (custom objects, lists, Entity Models, Linq to sql ect ect ….), Now the view can be strongly typed:

In the view, there is no casting, the designer of the view knows the type of all the data through the “Model”. Everyone knows about all the Objects passed by the controller.

 public ActionResult Index()
        {
            Object businessObject = new Object();
            List<Object> listOfBusinessObjects = new List<object>();
            Object businessObject2 = new Object();

            return View(new MvcApplication1.Models.IndexViewModel(businessObject,listOfBusinessObjects,
                businessObject2,"Welcome to ASP.NET MVC!");
        }

Also you can use MVC’s built-in validation. Everything is strong typed, explicit, readable, and all around better….

OH yeahhhhhhhh, what a relief. In the complex world of developing applications, I can not think of why I would ever have to use ViewData!?!? In the past I used it all the time, You can still create great applications, but the code and amount of work you need to put into this is not so great. I thought using strongly typed view was an Option, but it should be the only option (I am sure there will be disagreement on this).

One last thing…. View Model classes differ from your database model classes. The DB model represent the database tables, views etc. The View Model Class Combines all the data you need into one Object to represent the fields and components in your view.

Metal Siren time!

wooooooooooooooooooooooooooooooooooooooooo AHHHHHHHHHHHHHHHHH(vibarto!)HHHHHHHHHHHHHH!


2 Comments on “ASP.NET MVC 2.0 ViewData – Best practices, Abolish ViewData”

  1. Good day!This was a really exceptional website!
    I come from itlay, I was luck to seek your website in bing
    Also I learn much in your Topics really thank your very much i will come again


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.