Strongly typed view in ASP.NET MVC

December 21, 2009 § Leave a comment

When passing the model to MVC you have a couple of options.

Option 1: Passing un-typed model to the view

public ActionResult Product(string id)
    var product = new Product();

    product.ID = id;
    product.Name = "iPhone";

    ViewData["product"] = product;

In your view you have to cast the value in ViewData to the correct type as follows:

    var item = (Product)ViewData["product"];
    ID: <%= item.ID %>
    Name: <%= item.Name %>

Option 2: Pass a strongly typed model to the view

// ViewData["product"] = product;
ViewData.Model = product;

The Page directive of your view must specify the type it expects as follows:

<%@ Page Title="blah" ... Inherits="System.Web.Mvc.ViewPage<Product>" %>

Sometimes you may need to pass more than one object to the view. You can handle this by creating a new class that encapsulates all objects you need and pass an instance of that class to the view instead.


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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

What’s this?

You are currently reading Strongly typed view in ASP.NET MVC at


%d bloggers like this: