Wednesday 29 July 2015

[Asp.Net MVC] Passing Data from Controller to View

When we work with data in Asp.Net MVC, one important task is passing data from Controller to View for displaying. So how many way can we pass data from Controller to View? and which way should we choose? We are going to see in this post.

There are 3 ways:
  1. ViewData
  2. ViewBag
  3. Strongly Typed View

ViewData

ViewData is a dictionary, which will contains data to be passed between controller and views. Controller will add items to this dictionary and view reads from it.

Store data in ViewData in Controller:

ViewData["Employee"] = emp;
return View("MyView");

 Display data in View:

<div>
    @{
        WebApplication1.Models.Employee emp = (WebApplication1.Models.Employee)
            ViewData["Employee"];
    }

<b>Employee Details </b><br />
    Employee Name : @emp.FirstName @emp.LastName <br />
    Employee Name : @(emp.FirstName emp.LastName) <br />
    Employee Name : @ViewData["Employee"].FirstName @ViewData["Employee"].LastName <br />
    Employee Name : @(ViewData["Employee"].FirstName + " " + ViewData["Employee"].LastName) <br />
    Employee Salary: @emp.Salary.ToString("C")
</div>

ViewBag

ViewBag is just a wrapper for ViewData. ViewBag uses the dynamic feature of C# 4.0 and makes ViewData dynamic.

Store data in ViewBag in Controller:

ViewBag.Employee = emp;
return View("MyView");

 Display data in View:

<div>
    @{
        WebApplication1.Models.Employee emp = (WebApplication1.Models.Employee)
            ViewBag.Employee;
    }

<b>Employee Details </b><br />
    Employee Name : @emp.FirstName @emp.LastName <br />
    Employee Name : @(emp.FirstName emp.LastName) <br />
    Employee Name : @ViewBag.Employee.FirstName @ViewBag.Employee.LastName <br />
    Employee Name : @(ViewBag.Employee.FirstName + " " + ViewBag.Employee.LastName) <br />
    Employee Salary: @emp.Salary.ToString("C")
</div>

Problems with ViewData and ViewBag

ViewData and ViewBag is a good option for passing values between Controller and View. But in real time projects it’s not a good practice to use any of them. Let’s discuss couple of disadvantages of using ViewData and ViewBag.

Performance issues

Values inside the ViewData are of type Object. We have to cast the value to correct type before using it. It adds additional overhead on performance.

No Type safety and no compile time errors

If we try to cast values to wrong type or if we use wrong keys while retrieving the values, we will get runtime error. As a good programming practice, error should be tackled in compiled time.

No Proper connection between Data sent and Data Received


In MVC, controller and View are loosely connected to each other. Controller is completely unaware about what’s happening in View and View is unaware about what’s happening in Controller.
From Controller we can pass one or more ViewData/ViewBag values. Now when Developer writes a View, he/she have to remember what is coming from the controller. If Controller developer is different from View developer then it becomes even more difficult. Complete unawareness. It leads to many run time issues and inefficiency in development.

Understand strongly typed Views

Reason for all three problems of ViewData and ViewBag is the data type. Data type of values inside ViewData, which is “Object”.
Somehow if we were able to set the type of data which need to be passed between Controller and View problem will get solved and that’s wherestrongly typed Views comes to picture.

Step 1 – Make View a strongly typed view

Add following statement in the top of the View

@model WebApplication1.Models.Employee
 
Above statement make our View a strongly typed view of type Employee.

Step 2 – Display Data

Now inside View simply type @Model and Dot (.) and in intellisense you will get all the properties of Model (Employee) class.




Step 3 – Pass Model data from Controller Action method

Change the code in the action method to following.

Employee emp = new Employee();
emp.FirstName = "Sukesh";
emp.LastName="Marla";
emp.Salary = 20000;           
return View("MyView",emp);

Conclusion 

Although it's a best practice to use strongly typed view when we need to pass data from Controller to View, it's OK to use ViewBag when appropriate. To be more specific, anything you want strongly-typed in your view, then, needs to be on your model. If you have something you don't want on your model or that is one-off, then ViewBag is provided as a generic catch-all for all non-model data, which is why it is a dynamic.

Reference: http://www.codeproject.com/Articles/897559/Learn-MVC-in-days-Day

No comments:

Post a Comment