Tuesday, October 15, 2013

How to render grouped entities using strongly typed View in Asp.NET MVC?

In this post, we are going to learn how to show grouped entities using strongly typed Asp.net MVC View, for example, show all the products by subcategories as shown in the figure below. The first column shows the SubCategories and other columns show products. Another thing to notice is SubCategory’s Name property isn't populated more than once.  The style for just that row is colored and all other rows have background color as white.
image
I am using AdventureWorks2012 sample database for this example. I assume you know certain basics of Asp.Net MVC applications, little bit of LINQ and EntityFramework.  I am using database first approach with EntityFramework. 
  1. Create a basic Asp.net MVC4 Application. I am naming it as AspNetAjaxSamples101.  
  2. Add new empty Controller named HomeController
  3. Add a new ADO.NET Entity Data Model to your application.
  4. Open your HomeController and add following lines to your Index method.
We are passing the View an Object of type IEnumerable<IGrouping<string,AspNetAjaxSamples101.Models.Product>>. Add a new empty view to by right clicking on the View(ProductsBySubCategories.ToList()).
Copy the following code into your Index.cshtml page. Something about the code. Our view is a strongly typed view of type IEnumerable<IGrouping<string,AspNetAjaxSamples101.Models.Product>> that you can see on the top. Next piece of the puzzle is inside the tbody tag of table. First we do a foreach loop and get the group item then we iterate through each group item i.e. Product and show product details using for loop not foreach. The reason we use for loop is we want to know which row we are rendering. If it is the first row which we determine using the if statement then render SubCategory name using item.Key.ToString(). And if it is not the first row then skip the first td cell of the row and don’t show anything. Final piece in this project is styling. In the Site.css file add following style. In Index.cshtml page, inside second for loop if the i==0 then we assign class trsubheader to the row element of the table. So there you have it.

No comments:

Post a Comment