ViewData is used to pass data from controller to view and it consist of a null value when redirection occurs. ViewData is derived from ViewDataDictionary which is dictionary type and ViewData required typecasting. Following is the code scrap of ViewData in MVC
// Summary:
// Gets or sets the dictionary for view data.
//
// Returns:
// The dictionary for the view data.
public ViewDataDictionary ViewData { get; set; }
ViewData is a dictionary object that is derived from the ViewDataDictionary class. We will see how we can assign value to ViewData in Controller with a simple example for that create one new controller in the application and write code like as shown below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; namespace Tutorial4.Controllers
{
public class TestController : Controller
{
public ActionResult Index() {
ViewData["test"] = "hi Viewdata";
return View();
}
}
}
Now we will create one view to show data for that right click on controller à select add view give the name for that view (Index.cshtml). Open view file and write the following code to show data in the website
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
ViewData is used to pass data from controller to view and it consist of a null value when redirection occurs. ViewData is derived from ViewDataDictionary which is dictionary type and ViewData required typecasting. Following is the code scrap of ViewData in MVC
ViewData is a dictionary object that is derived from the ViewDataDictionary class. We will see how we can assign value to ViewData in Controller with a simple example for that create one new controller in the application and write code like as shown below
Now we will create one view to show data for that right click on controller à select add view give the name for that view (Index.cshtml). Open view file and write the following code to show data in the website
@{ViewBag.Title = "Index";
}
<h2>Index</h2>
@ViewData["test"]