Asp .Net MVC - SPLessons

ASP.Net MVC ViewData

Home > Lesson > Chapter 9
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

ASP.Net MVC ViewData

ASP.Net MVC ViewData

shape Introduction

ViewData is a dictionary which holds the objects derived from ViewDataDictionary class. ViewData is one of the way to pass data from the controller to view.

shape Description

View data value becomes null when the redirection occurs. That means ViewData has a short life. View Data is also used to maintain some data that means view data is used like state management technique in ASP.Net. ViewData is almost similar to TempData. ViewData Variable can be used only once in one Application.When gone for the next request, then the ViewData Variables are destroyed automatically. If wanted to give multiple requests. Then the ViewData is not useful. In general, Viewdata Variables are maintained by the View Context Object.

shape Syntax

ViewData[KeyName”]=Value;

shape Example

ViewData[“Name”]=” Jan”; ViewData[“a”]=”45″; ViewData[“b”]=”4.5″;

Accessing ViewData Variable

shape Description

ViewData Variable can be accessed from the view in three ways

shape Examples

The  below steps explain view data.

shape Step 1

Open the Visual studio 2013(whatever the version you have). Create an MVC Application. Add the controller and give the name as HomeController. Now, add view and give the name as the ViewDataExample.

shape Step 2

Write the following code under the HomeController.cs. [csharp] public ActionResult ViewDataExample() { ViewData["a"] = 10; ViewData["b"] = 45.5; ViewData["s"] = "James"; return View(); } [HttpPost] public ActionResult ViewDataExample(string x) { ViewData["X"]="Welcome to SPlessons Tutorials" return View(); } [/csharp]

shape Step 3

Write the following code under theViewDataExample.cshtml. [html] @{ ViewBag.Title = "ViewDataExample"; } <h2>TempDataExample</h2> <form name="f1" method="post"> <div> Value of a is :@ViewData["a"] Value of b is :@ViewContext.ViewData["b"] Value of s is :@ViewContext.Controller.ViewData["s"] Value of X is :@ViewData["X"] <input type="submit" value="SUBMIT" name="B1" /> </div> </form> [/html]

shape Step 4

Change the Action name as ViewDataExample in Routeconfig.cs.

shape Step 5

press f5 to run the application. The following output will appear.

shape Step 6

Click on the Submit button. Then the following window will appear.

shape Step 7

Observe the difference between two outputs. For the second request viewdata variables are destroyed.