Wednesday, 27 August 2014

ASP.NET MVC3 Vs MVC4 Vs MVC5

ASP.NET MVC 3

  • New Project Templates having support for HTML 5 and CSS 3.
  • Improved Model validation.
  • Razor View Engine introduced with a bundle of new features.
  • Having support for Multiple View Engines i.e. Web Forms view engine, Razor or open source.
  • Controller improvements like ViewBag property and ActionResults Types etc.
  • Unobtrusive JavaScript approach.
  • Improved Dependency Injection with new IDependencyResolver.
  • Partial page output caching

ASP.NET MVC 4

  • ASP.NET Web API, a framework that simplifies the creation of HTTP services and serving a wide range of clients. Follow to create your first ASP.NET Web API service.
  • Adaptive rendering and other look-n-feel improvements to Default Project Templates.
  • A truly Empty Project Template.
  • Based on jQuery Mobile, new Mobile Project Template introduced.
  • Support for adding controller to other project folders also.
  • Task Support for Asynchronous Controllers.
  • Controlling Bundling and Minification through web.config.
  • Support for OAuth and OpenID logins using DotNetOpenAuth library.
  • Support for Windows Azure SDK 1.6 and new releases.

ASP.NET MVC 5

Creating your first ASP.NET MVC 5 Application in 4 simple steps
  • Bootstrap replaced the default MVC template.
  • ASP.NET Identity for authentication and identity management.
  • Authentication Filters for authenticating user by custom or third-party authentication provider.
  • With the help of Filter overrides, we can now override filters on a method or controller.
  • Attribute Routing is now integrated into MVC 5.

Passing data from Controller to View in ASP.NET MVC

ASP.NET MVC is a framework that facilitates building web applications based on MVC (Model-View-Controller) design pattern. Request coming from client reaches the Controller through URL Rewriting Module. Controller decides which model to use in order to fulfill the request. Further passing the Model data to View which then transforms the Model data and renders response to client as shown in following basic level request flow diagram.
ASP.NET MVC Request Flow
In this ASP.NET MVC Tutorial, we will discuss and implement different options to pass data from ASP.NET MVC Controller to View. Following are the available options to pass data from a Controller to View in ASP.NET MVC:
  • ViewBag
  • ViewData
  • TempData
If we want to maintain state between a Controller and corresponding View- ViewData and ViewBag are the available options but both of these options are limited to a single server call (meaning it’s value will be null if a redirect occurs). But if we need to maintain state from one Controller to another (redirect case), then TempData is the other available option.
It’s common that initially it might be a bit difficult for a ASP.NET WebForms developer to digest above flow and need for options to pass data from Controller to View. Because in WebForms approach, Controller and View are tightly coupled to each other.

ViewBag Example

As we discussed earlier that ViewBag and ViewData serves the same purpose but ViewBag is basically a dynamic property (a new C# 4.0 feature) having advantage that it doesn’t have typecasting and null checks.
So, In order to pass data from Controller to View using ViewBag, we will modify our EmployeeController code as follows:
 public class EmployeeController : Controller
 {
           // GET: /Employee/
          public ActionResult Index()
         {
                     ViewBag.EmployeeName = “Muhammad Hamza”;
                     ViewBag.Company = “Web Development Company”;
                     ViewBag.Address = “Dubai, United Arab Emirates”;                     
                     return View();
         }
  }
And to get Employee details passed from Controller using ViewBag, View code will be as follows:
  <body>
    <div>
          <h1>Employee (ViewBag Data Example)</h1>
          <div>
                       <b>Employee Name:</b> @ViewBag.EmployeeName<br />
                      <b>Company Name:</b> @ViewBag.Company<br />
                      <b>Address:</b> @ViewBag.Address<br />
          </div>
    </div>
  </body>
In order to see the above changes in action run the solution, we will find the following output.
ViewBag Example

ViewData Example

As compared to ViewBag, ViewData is a dictionary object which requires typecasting as well as null checks. Same above implementation using ViewData can be achieved as follows:
 public class EmployeeController : Controller
 {
           // GET: /Employee/
          public ActionResult Index()
         {
                     ViewData["EmployeeName"] = “Muhammad Hamza”;
                     ViewData["Company"] = “Web Development Company”;
                     ViewData["Address"] = “Dubai, United Arab Emirates”;                     
                     return View();
         }
  }
And to get Employee details passed from Controller using ViewBag, View code will be as follows:
  <body>
    <div>
          <h1>Employee (ViewBag Data Example)</h1>
          <div>
                       <b>Employee Name:</b> @ViewData["EmployeeName"]<br />
                      <b>Company Name:</b> @ViewData["Company"]<br />
                      <b>Address:</b> @ViewData["Address"]<br />
          </div>
    </div>
  </body>
Run the application to view the following output.
ViewData Example

Using TempData in ASP.NET MVC

TempData in ASP.NET MVC is basically a dictionary object derived from TempDataDictionary. TempData stays for a subsequent HTTP Request as opposed to other options (ViewBag and ViewData) those stay only for current request. So, TempdData can be used to maintain data between controller actions as well as redirects.
Note: Just like ViewData, typecasting and null checks required for TempData also in order to avoid errors.
Let’s see how we can use TempData in a practical scenario to pass data from one controller action to another.
   //Controller Action 1 (TemporaryEmployee)
   public ActionResult TemporaryEmployee()
  {
                  Employee employee = new Employee
                  {
                          EmpID = “121″,
                          EmpFirstName = “Imran”,
                          EmpLastName = “Ghani”
                  };                   
                  TempData["Employee"] = employee;
                  return RedirectToAction(“PermanentEmployee”);
  }   
 
   //Controller Action 2(PermanentEmployee)
   public ActionResult PermanentEmployee()
  {
                 Employee employee = TempData["Employee"] as Employee;
                 return View(employee);
   }
As in above example, we store an employee object in TempData in Controller Action 1 (i.e. TemporaryEmployee) and retrieve it in another Controller Action 2 (i.e. PermanentEmployee). But If we try to do the same using ViewBag or ViewData, we will get null in Controller Action 2 because only TempData object maintains data between controller actions.
An important thing about TempData is that it stores contents in Session object. Then one may raise a question that  “What’s the difference between TempData in ASP.NET MVC and Session?” or “Why we have TempData dictionary object?, Why can’t we use the Session object directly?

ASP.NET MVC TempData Vs Sessions

Although ASP.NET MVC TempData stores it’s content in Session state but it gets destroyed earlier than a session object. TempData gets destroyed immediately after it’s used in subsequent HTTP request, so no explicit action required. If we use a Session object for this purpose, we would have to destroy the object explicitly.
It’s best fit for scenarios when:
  • we need to preserve data from current to subsequent request.
  • passing error message to an error page.

No comments:

Post a Comment