ViewData in MVC with Best Top 2 Example

ViewData in MVC is a dictionary of objects that are stored and retrieved using strings as keys. ViewData in MVC is used for transfers data from the Controller to View, not vice-versa. It is used to transfer data from Controller to View. Since ViewData is a dictionary, it contains key-value pairs where each key must be a string.

In this topic, I am going to discuss the ideas about ViewData in MVC with example. Please read our previous articles before moving on to this article where we discussed the ViewBag in MVC. We are going to discuss the following contents which are related to ViewData in MVC.

ViewData in MVC

  • ViewData also used to passing/storing data from controller to view, not vice-versa..
  • If you initialise objects in ViewData, those objects become accessible in the view.
  • ViewData is a dictionary and It derived from ViewDataDictionary class. You can access by “Key/Value” pair.
  • It requires typecasting for the complex object.
  • You must be check for null values to avoid error.
  • It’s value becames null when page is redirected.
  • It’s live only during the current request.
  • ViewData is Faster than ViewBag.
  • ViewData is introduced in MVC 1.0 but It also works with MVC 1.0 and above.
public ViewDataDictionary ViewData { get; set; }

This defines under ControllerBase class.

ViewData in ASP.NET MVC with String Type

EmployeeController.cs

public class EmployeeController : Controller
{
	public ActionResult Index ( )
	{
		ViewData["Name"] = "www.infosyntax.com";
		return View();
	}
}

Index.cshtml

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>

<h2>Welcome to @ViewData["Name"]</h2>

Output –

ViewData in MVC

ViewData in MVC with Complex Type

EmployeeController.cs

public class EmployeeController : Controller
{
	public ActionResult Index ( )
	{
		ViewData["Name"] = "www.infosyntax.com";
		return View();
	}
	
	public ActionResult ComplexIndex ( )
	{
		List Employee = new List();
		Employee.Add("King");
		Employee.Add("Lipsh");
		Employee.Add("Rio");
		ViewData["Employee"] = Employee;
		return View();
	}	
}	

ComplexIndex.cshtml

@{
    ViewBag.Title = "ComplexIndex";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>
Complex Index</h2>
<ul>
@foreach (var employee in ViewData["Employee"] as List)
{
    <li>@employee</li>
}
</ul>

Output –

Warm UP – ViewData in MVC

  • ViewData also used to passing/storing data from controller to view, not vice-versa..
  • ViewData is a dictionary and It derived from ViewDataDictionary class. You can access by “Key/Value” pair.
  • It requires typ for the complex object.
  • You must be check for null values to avoid error.
  • It’s live only during the current request.
  • ViewData is Faster than ViewBag.

ViewData from Microsoft

Leave a Comment

Your email address will not be published. Required fields are marked *