Thursday, February 21, 2013

How do Strongly Typed Views work in MVC


Most of us know that in MVC we can have loosely coupled Views or

strongly typed Views but what difference does it make.

 

1)     Strongly typed views give us the benefit of intellisense, on the other hand intellisense is not available is loosely typed views.

 

2)     So how do we pass the data into a loosely typed view by using the Viewbag or ViewData, then what about strongly typed views ???? the big question is they look different but is there really a big difference other than it knowing the type for intellisense.

Ex:


public class HomeController : Controller
{
   public ActionResult Sample() {
        ViewBag.Message = "Hello World. Welcome to ASP.NET MVC!";
         return View("Sample");
}


}


And then access the content in the loosely typed view as shown below.

@{
  Layout = null;

}
 

 @ViewBag.Message

Now let’s see how it works in a strongly typed View, and you will for sure be like I did not know...just like I did. So this is how the Controller action would look:

public ActionResult List()
{

  var peanuts = new List();

     for (int i = 0; i < 10; i++)
    {
      peanuts.Add(new Nut {Title = "Peanut " + i } );
    }
   return View(peanuts);}


Now, let’s concentrate on the blue text in the code above, what is happening under the hood here is basically the same... View(peanuts) is assigning the value of peanuts to the ViewBag or ViewData… but that’s exactly what we do for loosely typed view.
 

 Yes, but only difference is we specifically assign to the Model property on the ViewData. ViewData is of type ViewDataDictionary which has a Model property [ So yes ViewData is not just a dictionary but a wrapper on top of it with some extra properties ], which is where the View(peanuts) actually assigns the value under the hood you can do this too as shown below

 ViewData.Model = peanuts;

Now, this is how code will look in your View to access the peanuts

@model IEnumerable
@foreach (Nut n in Model) {
 n.Title
}

 

 Model above is nothing but the property of Model from the ViewDataDictionary that is

implicitly referered to at runtime and now there is no missing link I guess now you know there basically is no difference in the strongly typed and loosely typed views except the intellisense.

 

 

 

I hope you did not know this, If you already did do not waste anymore time today...lol

 

No comments:

Post a Comment