MVC 3
ViewData:
There are some points about it describe below
- Gets or sets a
dictionary that contains data to pass between the controller and the view.
- Created in Controller
where it is passed to the view.
- The Objects which
accessible using strings as Keys.
- It is derived from
ViewDataDictonary Class.
- Needs to cast values
and perform error checking for null values that does not exist.
- [Authorize]
public ActionResult
Edit(int id)
{
Dinner dinner = dinnerRepository.GetDinner(id);
ViewData["Countries"] = new SelectList(PhoneValidator.AllCountries,
dinner.Country);return View(dinner);
}
<%= Html.DropDownList("Country",
ViewData["Countries"] as SelectList)
%>
ViewBag:
- It acts as a wrapper
around the view data object which allows creating dynamic properties for the
view bag. It enables great in data accessing facilities.
- It access data in
dynamic fashion instead of using magic strings
- It is easier to store
and retrieve key/value pairs in backing store used by view data.
- We don't have to type
cast. It is better and easier way to access data over viewdata. On the other
hand, there are pretty much drawbacks with viewbag such as it does not
support intellisense to get the list of properties specified in the
controller. It also does not accepts the dynamic data to pass into html
helper methods of System.Web.Mvc.HtmlHelpers.
public
ActionResult Index()
{
List<string>
colors = new List<string>();
colors.Add("red");
colors.Add("green");
colors.Add("blue");
ViewBag.ListColors = colors; //colors is List
ViewBag.DateNow = DateTime.Now;
ViewBag.Name = "Raj";
ViewBag.Age = 25;
return View();
}
<p>
My name is
<b><%: ViewBag.Name %></b>,
<b><%: ViewBag.Age %></b> years old.
<br />
I like the following colors:
</p>
<ul id="colors">
<% foreach (var color
in ViewBag.ListColors) { %>
<li>
<font color="<%: color %>"><%: color
%></font>
</li>
<% } %>
</ul>
<p>
<%: ViewBag.DateNow %>
</p>
TempData:
- It is stored in
session, the way to persist data across single request. It is used to store
the validation errors before redirecting to the previous page.
- It mainly deals with
processing current and subsequent request when you are sure that it is
redirecting to the next view. They are destroyed after the request made.
- It is available for
temporary for a single request where it passes messages between controllers
- It is a type of fire
and forget mechanism. If you want to use session or high scale in throughput
do not hesitate to TempData.
- [ControllerAction]
public
void Create(int
id)
{
Product prod = new Product();
prod.UpdateFrom(Request.From);
if(prod.Validate())
{
prod.Save();
RedirectToAction("List");
}
else
{
TempData["ErrorMessage"] =
"Invalid entry. Try again.";
RedirectToAction("New");
}
}
//New.aspx:
<%
if(TempData.ContainsKey("ErrorMessage")
{ %>
Error happened: <%= TempData["ErrorMessage"]
%>
<% } %>
rest of the HTML ...