MVC Strongly Typed Views

This article is a case study which you may need to read a general information about MVC first. Click here for basics.

Using ViewData / ViewBag in ASP.NET MVC applications is an easy way to pass data between controller and view but it is not a good practice. Read this article for further details.

In order to eliminate the inefficiencies of the ViewData / ViewBag we will make the View a strongly typed View based on a model selected. In order to do that, we need to add a @model directive on top of our view class (MyAction2 on the demo application. Read more about our demo application if you need.)

@model MVC_DemoApp.Models.Demo

In our demo application, view has the following line of declaration for the customers:

@{
 ViewBag.Title = "MyAction2";

MVC_DemoApp.Models.Customer[] customers =
 (MVC_DemoApp.Models.Customer[])ViewData["Customers"];
}

And we were referencing the customers entries like:

@foreach (MVC_DemoApp.Models.Customer c in customers)
 {
 <tr>
 <td>@c.customerID</td>
 <td>@c.customerName</td>
 <td>@c.customerCountry</td>
 </tr>
 }

 

After making our view a strongly type view we change the way how we display the customer data as follows:

 

@model MVC_DemoApp.Models.Demo

@{
ViewBag.Title = "MyAction2";
MVC_DemoApp.Models.Customer[] customers2 = Model.customerList();
}

---

 @foreach (MVC_DemoApp.Models.Customer c in customers2)
 {
 <tr>
 <td>@c.customerID</td>
 <td>@c.customerName</td>
 <td>@c.customerCountry</td>
 </tr>
 }

 

By this way we skip using the ViewData / ViewBag and we dont make any type conversions.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: