With the advent of MVC it is imperative for all programmers to understand the different ways this framework provides to share data from Controller to View. Each solution has its pros and cons. But my advice to you is stick to the method which is most comfortable to you and accepted by your team lead.
Different ways of sharing data
· ViewBag
· TempData
· Session
· Models
· View Model
ViewBag
This property enables the programmer to share values from the controller to the view. It is a dynamic object, thus has no predefined properties and hence no intellisense. In the view, programmer can retrieve those values by using same name for the property.
If any kind of redirection happens this property is lost thus it is closely coupled with the current request/response.
Let us look at a small example
HomeController.cs
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.MyOwnProperty = "This is a killer tag line";
return View();
}
}
Index.cshtml
<div >
<h1>@ViewBag.MyOwnProperty</h1>
div>
Output
TempData
The value stored in TempData property lives for only one request. The default TempData provider uses session state for storage. If session state is disabled, the default TempData provider will be disabled. It needs typecasting for returning data and if it is null it will raise an error.
TempData is a session-backed temporary storage dictionary that is available for one single request. It’s great to pass messages between controllers.
Session
Session is an object that is derived from HttpSessionState class. This object is used to persist data over the whole session but it should be used judiciously or else it will bog down the server by having to store extra information that may only be necessary across a redirect.
The correct way to store these temporary variables across a redirect is by using the TempData dictionary.
HomeController.cs
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.MyOwnProperty = "This is a killer tag line";
Session = "some sesson value";
return View();
}
public ActionResult About()
{
string sessionval;
if(Session!=null)
sessionval = Session as string;
return View();
}
}
Index.cshtml
<div >
<h1>@ViewBag.MyOwnProperty</h1>
<h3>@Session</h3>
div>
Model
It is recommended by all that Models should be used to pass data from a Controller to View. This forces us to create strongly typed view, these views in turn are able to access the server side object.
Model classes can be of two main types known as Data Model and Domain Model. As the name suggests the first one maps to our entities in our DB the second one maps to the entities represented in our domain. More often than not the model that you will pass on to the view will be a Domain Model.
Let us create our first model called Student in our project inside the Model folder
Student.cs
public class Student
{
public int id { get; set; }
public string name { get; set; }
public int age { get; set; }
}
Make sure you have compiled the project. Go to your Home Controller and add the using directives for including the projectname.Models
HomeController.cs
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.MyOwnProperty = "This is a killer tag line";
Session = "some sesson value";
Student obj = new Student
{
id = 1,
name = "rakesh",
age = 23
};
return View(obj);
}
}
Now lets add the view which will be strongly coupled with our student class.
Index.cshtml
@model Trial.Models.Student
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Indextitle>
head>
<body>
<div>
<table>
<tr>
<td>
@Html.LabelFor(m => m.id)
td>
<td>
@Html.EditorFor(m => m.id)
td>
tr>
<tr>
<td>
@Html.LabelFor(m => m.name):
td>
<td>
@Html.EditorFor(m => m.name)
td>
tr>
<tr>
<td>
@Html.LabelFor(m => m.age):
td>
<td>
@Html.EditorFor(m => m.age)
td>
tr>
table>
div>
body>
html>
Output
View Model
Problem with the above given solution of Model is that the View is now coupled with a single model class. Unfortunately the real world software’s are not that straight forward and you will run into requirement where the controller needs to send objects of two or more different classes to the same view. As you have already studied that View can be bound to a single Model.
In such a scenario we have another type of Model called View Model , these are nothing but classes which hold objects of two or more classes inside itself as properties. Let’s assume that each student has a student supervisor associated with him/her. We need to send the StudentSupervisor object to the view to be shown with the student data. (Obviously this can be done in a different manner by setting up relationship etc, lets keep it simple for now)
StudentSupervisor.cs
public class StudentSupervisor
{
public int id { get; set; }
public string name { get; set; }
public float experience { get; set; }
public bool certified { get; set; }
}
StudentViewModel
public class StudentViewModel
{
public Student studentObj { get; set; }
public StudentSupervisor supervisorObj { get; set; }
}
Make sure you bind the view with StudentViewModel class this time.
HomeController.cs
public class HomeController : Controller
{
public ActionResult GetStudent()
{
Student studentObj = new Student
{
id = 1,
name = "rakesh",
age = 23
};
StudentSupervisor supervisorObj = new StudentSupervisor
{
id = 123,
name = "Strict Penny",
experience = 23,
certified = true
};
StudentViewModel obj = new StudentViewModel {
studentObj=studentObj,
supervisorObj=supervisorObj
};
return View(obj);
}
}
Index.cshtml
@model Trial.Models.StudentViewModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>GetStudenttitle>
head>
<body>
<table>
<tr>
<td>
@Html.LabelFor(m => m.studentObj.id)
td>
<td>
@Html.EditorFor(m => m.studentObj.id)
td>
tr>
<tr>
<td>
@Html.LabelFor(m => m.studentObj.name):
td>
<td>
@Html.EditorFor(m => m.studentObj.name)
td>
tr>
<tr>
<td>
@Html.LabelFor(m => m.studentObj.age):
td>
<td>
@Html.EditorFor(m => m.studentObj.age)
td>
tr>
<tr>
<td colspan="2">
Supervisor is @Model.supervisorObj.name with experience of @Model.supervisorObj.experience years
td>
tr>
table>
body>
html>
Conclusion
This post just tries to bring out the different ways you can use to communicate with the MVC view and the author hopes that the reader appreciates the extreme ease of use this framework provides for you.