Thursday 26 December 2013

Various ways to pass the data between the Controller and the View

In this article we are going to see the various ways to pass the data between the Controller and the View. ViewBag and the ViewData are the two things which are used to pass the data between the controller and the View

ViewBag
    This is a dynamic object in which all values are stores as property in the controller, so when in the view the values are referred as property, there we can't check the compile time error in ViewBag, Internally if we see the ViewBag is stored as name/value pairs of ViewData dictionary

public class HomeController : Controller
    {

        public ViewResult Sample()
        {
            ViewBag.Employees = new List<string>() { "Rajesh", "Suresh", "Ramu", "Siva"};           
            return View();
        }
}

@{
    ViewBag.Title = "Employee Records";
}

<h2>Employee Names</h2>
<ul>
@foreach (string empname in ViewBag.Employees)
{
    <li>@empname</li>
}
</ul>




ViewData
    This is a Dictionary key values pair object in which values are stored against a string key in controller and it can be referred  by the key from the ViewData, the return type of the ViewData is object so we have to type cast to the original type.


       public ViewResult Sample()
        {
            ViewData["Employees"] = new List<string>()
{
"Rajesh",
"Suresh",
"Ramu",
"Siva"
};           
            return View();
        }




@{
    ViewBag.Title = "Employee Records";
}

<h2>Employee Names</h2>
<ul>
@foreach (string empname in (List<string>)ViewData["Employees"])
{
    <li>@empname</li>
}
</ul>

Errors from the both object can be seen only in Runtime. 

output:




From this article you can see the various ways to pass the value from the Controller to the View.

No comments:

Post a Comment