|
Viewdata is the collection of
state that is passed to a view. A view should get all the information it needs
from the viewdata. It contains key/value pairs as well as some special
properties, such as Model. Viewdata is accessible on the controller as well. The
controller is responsible for filling the viewdata dictionary with objects. When
a view is executing, it will pull various object from viewdata while it is
rendering. If an expected object is not present, then you will see the same type
of exception present in any code using a dictionary collection in .Net.
How to use View Data?
Here, I am going to explain how to use ViewData in View to get the information
dynamically through Controller and Model.
In
HomeController.cs, we set the Current Date and Time by using
Now property of DateTime class in
the field of ViewData property.
using System;
using System.Web.Mvc;
using ViewData.Models;
namespace ViewData.Controllers
{
public class
HomeController :
Controller
{
public ActionResult
Index()
{
ViewData["CurrentTime"] =
DateTime.Now.ToString();
//set the current date and
time in ViewData field
return View(new
ModelClass());
}
}
}
In ModelClass.cs,
we created a property named as
FirstName that return a name.
namespace ViewData.Models
{
public class
ModelClass
{
public string
FirstName
{
get
{
return
"Rohit";
}
}
}
}
After setting the data in ViewData, here in View we
retrieved the information in View through ViewData.
<%@
Page Language="C#" Inherits="System.Web.Mvc.ViewPage<ViewData.Models.ModelClass>"
%>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Index</title>
</head>
<body>
<div>
<!--Getting data from Model ViewData -->
<h3>Hello!
<%: ViewData.Model.FirstName
%>
<br
/><br
/>
<!--Getting data from Controller View Data
-->
The current date and time is
<%: ViewData["CurrentTime"]
%></h3>
</div>
</body>
</html>
The above code display output like below:
|