What is ViewData?
Introduction
This article demonstrates an interesting and very useful concept in ASP.NET MVC.
Question: What is ViewData?
In simple terms "ViewBag is a data holder that enables definition of a key-value pair and that holds the data that can be passed from controller to view".
Step 1: Create a new ASP.NET MVC application
Step 2: Adding New Model
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace ViewDataDemoApp.Models
{
public class Addition
{
[Required(ErrorMessage = "Please Enter FirstNumber")]
public int FirstNumber { get; set; }
[Required(ErrorMessage = "Please Enter SecondNumber")]
public int SecondNumber
{
get;
set;
}
}
}
Step 3: Adding New Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ViewDataDemoApp.Models;
namespace ViewDataDemoApp.Controllers
{
public class AdditionController : Controller
{
//// GET: /Addition/public ActionResult Index(Addition addition)
{
ViewData["AddMessage"] = "Addition Result is: ";
ViewData["Result"] = addition.FirstNumber + addition.SecondNumber;
if ((int)ViewData["Result"] < 1)
{
ViewData["AddMessage"] = string.Empty;
ViewData["Result"] = string.Empty;
}
return View();
}
}
}
Step 4: Adding New View
@model ViewDataDemoApp.Models.Addition@
{ ViewBag.Title = "Addition Operation Using ViewData"; }<h2>
Addition Operation Using ViewData</h2>
<br />
@using (Html.BeginForm()) {@Html.ValidationSummary(true)<fieldset>
<legend>Addition</legend>
<div class="editor-label">@Html.LabelFor(model => model.FirstNumber)</div>
<div class="editor-field">@Html.EditorFor(model => model.FirstNumber)@Html.ValidationMessageFor(model => model.FirstNumber)</div>
<div class="editor-label">@Html.LabelFor(model => model.SecondNumber)</div>
<div class="editor-field">@Html.EditorFor(model => model.SecondNumber)@Html.ValidationMessageFor(model => model.SecondNumber)</div>
<p>@ViewData["AddMessage"] @ViewData["Result"]</p>
<br />
<p>
<input type="submit" value="Add" /></p>
</fieldset> }<div>@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {@Scripts.Render("~/bundles/jqueryval")
}
Step 5: The output for the application looks as in the following: