Tuesday, 11 March 2014

Passing state between actio method in 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.
Note: This behavior is new in ASP.NET MVC 2. In earlier versions of ASP.NET MVC, the value 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) || String.IsNullOrEmpty(lastName))
        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" />

No comments:

Post a Comment