Passing Data in an ASP.NET MVC Application

Visual Studio 2010

The ASP.NET MVC framework provides page-level containers that can pass data between controllers and views. This topic explains how to pass both weakly typed and strongly typed data in an MVC application. It also explains how to pass temporary state data between action methods.

To render a view, you call the View method of the controller. To pass data to the view, you use the ViewData property of the ViewPage class. This property returns a ViewDataDictionary object that has case-insensitive string keys. To pass data to the view, you can assign values to the dictionary, as shown in the following example:

List<string> petList = new List<string>();
petList.Add("Gold fish");
petList.Add("Mountain lion");

ViewData["Pets"] = new SelectList(petList);

If you call the View method without parameters (as shown in the previous example), the controller object's ViewData property is passed to the view that has the same name as the action method.

In the view page, you can access the ViewData property to obtain data that was passed to the view. The ViewData property is a dictionary that supports an indexer that accepts dictionary keys.

The following example shows the markup for a view that displays the data in an HTML form and enables the user to modify values and make selections.

<h2><%= Html.Encode(ViewData["Message"]) %></h2>
<br /><br />
<% using(Html.BeginForm("HandleForm", "Home")) %>
<% { %>
    Enter your name: <%= Html.TextBox("name") %>
    <br /><br />
    Select your favorite color:<br />
    <%= Html.RadioButton("favColor", "Blue", true) %> Blue <br />
    <%= Html.RadioButton("favColor", "Purple", false)%> Purple <br />
    <%= Html.RadioButton("favColor", "Red", false)%> Red <br />
    <%= Html.RadioButton("favColor", "Orange", false)%> Orange <br />
    <%= Html.RadioButton("favColor", "Yellow", false)%> Yellow <br />
    <%= Html.RadioButton("favColor", "Brown", false)%> Brown <br />
    <%= Html.RadioButton("favColor", "Green", false)%> Green 
    <br /><br />
    <%= Html.CheckBox("bookType") %> I read more fiction than non-fiction.<br />
    <br /><br />
    My favorite pet: <%= Html.DropDownList("pets") %>
    <br /><br />
    <input type="submit" value="Submit" />
<% } %>

When you pass data between a view and a controller by using the ViewData property of the ViewPage class, the data is not strongly typed. If you want to pass strongly typed data, change the @ Page declaration of the view so that the view inherits from ViewPage<TModel> instead of from ViewPage, as shown in the following example:

<%@ Page Inherits="ViewPage<Product>" %>

ViewPage<TModel> is the strongly-typed version of ViewPage. The ViewData property of ViewPage<TModel> returns a ViewDataDictionary<TModel> object, which contains strongly typed data for the view based on a model. The model is a class that contains properties for each data item that you want to pass. (A simpler approach to creating a strongly typed view page is to use the Add View dialog box.)

The following example shows the definition of a typical data model class named Person.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace MvcDataViews.Models
    public class Person
        [Required(ErrorMessage = "The ID is required.")]
        public int Id { get; set; }

        [Required(ErrorMessage = "The name is required.")]
        public string Name { get; set; }

        [Range(1, 200, ErrorMessage = "A number between 1 and 200.")]
        public int Age { get; set; }

        [RegularExpression(@"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}", 
            ErrorMessage = "Invalid phone number.")]
        public string Phone { get; set; }

            ErrorMessage = "Invalid email address.")]
        public string Email { get; set; }

The following example shows a view that enables the user to modify the values of a Person object and to submit the changes for update.

The following example shows the action method that receives a Person object from the Edit view, checks its validity against the model, updates a list of Person objects, and then redirects to the Index action.

<HttpPost()> _
Function Delete(ByVal p As Person) As ActionResult
    For Each pn As Person In people
        If (pn.Id = p.Id) Then
            Exit For
        End If

    Return RedirectToAction("Index")
End Function

For more information and links to downloadable samples that illustrate strongly typed views, see How to: Validate Model Data Using DataAnnotations Attributesand Walkthrough: Using Templated Helpers to Display Data in ASP.NET MVC.

Action methods might have to pass data to another action, such as if an error occurs when a form is being posted, or if the method must redirect to additional methods, as might occur when the user is directed to a login view and then back to the original action method.

An action method can store data in the controller's TempDataDictionary object before it calls the controller's RedirectToAction method to invoke the next action. The TempData property value is stored in session state. Any action method that is called after the TempDataDictionary value is set can get values from the object and then process or display them. The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request.


This behavior is new in ASP.NET MVC 2. In earlier versions of ASP.NET MVC, the values in TempData was available only until the next request.

The following example shows a data class that is used to trap an error and to transfer data between actions.

public class InsertError
    public string ErrorMessage { get; set; }
    public string OriginalFirstName { get; set; }
    public string OriginalLastName { get; set; }

// CustomersController

public ActionResult InsertCustomer(string firstName, string lastName)
    // Check for input errors.
    if (String.IsNullOrEmpty(firstName) ||
        InsertError error = new InsertError();
        error.ErrorMessage = "Both names are required.";
        error.OriginalFirstName = firstName;
        error.OriginalLastName = lastName;
        TempData["error"] = error;
        return RedirectToAction("NewCustomer");
    // No errors
    // ...
    return View();

public ActionResult NewCustomer()
    InsertError err = TempData["error"] as InsertError;
    if (err != null)
        // If there is error data from the previous action, display it.
        ViewData["FirstName"] = err.OriginalFirstName;
        ViewData["LastName"] = err.OriginalLastName;
        ViewData["ErrorMessage"] = err.ErrorMessage;
    // ...
    return View();

The following example shows the markup for a view that accepts user input and displays an error message if an error occurs.

<form action="/Home/InsertCustomer">
  <% if (ViewData["ErrorMessage"] != null) { %>
    The following error occurred while inserting the customer data:
    <br />
    <%= ViewData["ErrorMessage"] %>
    <br />
  <% } %>

  First name: 
  <input type="text" name="firstName" value="<%= ViewData["FirstName"] %>" />
  <br />
  Last name: 
  <input type="text" name="lastName" value="<%= ViewData["LastName"] %>" />
  <br />    
  <input type="submit" value="Insert" />

Community Additions