Page 1 of 1

MVC 3 WebGrid inside a WebGrid

#1 Nakor  Icon User is offline

  • Professional Lurker
  • member icon

Reputation: 444
  • View blog
  • Posts: 1,492
  • Joined: 28-April 09

Posted 30 April 2011 - 12:15 AM

Today I want to look at the WebGrid control for asp.net MVC and WebMatrix WebPages a little more in depth. If you would like a quick introduction to the WebGrid I have a quick tutorial here. I have been working on a small MVC site implementing my fork of the CherryTomatoes library by which is a library that makes use of an API put out by RottenTomatoes.com. This enables you to do searches based on movie titles and then display a list of results. A problem I was having with displaying the results was caused because the result is a complex object consisting of a multiple movie objects which look are structured as follows:

        public int RottenTomatoesId { get; set; }
        public string Title { get; set; }
        public int Year { get; set; }
        public string MpaaRating { get; set; }
        public int? Runtime { get; set; }
        public string Synopsis { get; set; }
        public List<ReleaseDate> ReleaseDates { get; set; }
        public List<Rating> Ratings { get; set; }
        public List<string> Genres { get; set; }
        public List<string> Directors { get; set; }
        public List<CastMember> Cast { get; set; }
        public MovieLinkCollection Links { get; set; }
        public PosterCollection Posters { get; set; }



So the main object returned is basically a list of these Movie objects which contains multiple lists of strings and lists of objects. The main point of all this is just to let you know that there are some interesting things that can be done even with complex objects using the WebGrid.

So I started by declaring the main object as the Model for my page, and then set the Model as the datasource my WebGrid. I'm not going to go into the whole controller side of this as this is a tutorial for the WebGrid and not on using the CherryTomato library.

@model CherryTomato.Entities.MovieSearchResults

@{
    ViewBag.Title = "Movie Search";
    Layout = "~/Views/Shared/_Layout.cshtml";
    string title = string.Empty;
    
    var grid = new WebGrid(@Model, canPage: true);
}




This is a very basic setup. I have set the model as the datasource for the webgrid and I've told it that I want paging to be enabled. Nothing too fancy. To get a WebGrid to display it's contents you can use one of two methods, either GetHtml() or Table(). From what I've seen so far they both provide the same results and are interchangeable with one another. So let's see what the result of this looks like so far. At this point my entire page looks like this.

@model CherryTomato.Entities.MovieSearchResults

@{
    ViewBag.Title = "Movie Search";
    Layout = "~/Views/Shared/_Layout.cshtml";
    string title = string.Empty;
    
    var grid = new WebGrid(@Model, canPage: true);
}
<div id="Results">
<form action="" method="post">
<input type="text" name="q" value="" />
<input type="submit" name="btnSubmit" value="Search" />
</form>   

@if (@Model != null && @Model.Count > 0)
{   
    @grid.GetHtml()
}    



and the results look like this...

Attached Image

Besides the total lack of formatting, the first thing you might notice is that the WebGrid is only displaying the simple properties for each of the movie items and not any of the List items. For some circumstances this might be fine, but what if you want to display the cast members for the movie as well? Do we need to create another WebGrid and display them separately by somehow linking them to the primary table or can we display them within the current WebGrid? Well, you can do either but right now I'm going to show you how to display the list within the current WebGrid.

Alright, so the nice thing about the WebGrid is that it also allows you to customize each column, from specifying the header text to the format of each cell that gets displayed in that column. We're going to take full use of this ability to format the cells to display a table of of cast objects, containing the name of the actor and the character(s) they portray, within the cell of the WebGrid.

So to get our feet wet with formatting a cell lets start by making sure our title column doesn't stretch all the way across the screen if a movie title is longer than average.

@grid.GetHtml(        
        columns: grid.Columns(
            grid.Column("Title", "Movie", @<text><div style='width: 10em'>@item.Title</div></text>),



Ok, quick explanation. With the WebGrid we can make use of named parameters to specify which property we are wanting to set. In this case we're working with the columns property as indicated by putting "columns:" before grid.Columns. Next we pass a grid.Column object into the grid.Columns and tell it the name of the column, the header text, and then we specify the format of the data cells. In this instance each table cell for the title column will contain a div element that is 10em wide that contains the title for the movie. This is a very simple example of formatting a cell. The nice thing about the format parameter in the grid column is that it can also take a lambda expression, which allows us to a lot more complex things such as using foreach loops to loop through a simple list or even creating another WebGrid within the first WebGrid, which is what we're going to do here since we're dealing with a list of objects with multiple properties we want to display, one of which is also a List of strings. For simplicity I'm only going to work with the Title column and the Cast column in the next example.

First the code:
@grid.GetHtml(        
        columns: grid.Columns(
            grid.Column("Title", "Movie", @<text><div style='width: 10em'>@item.Title</div></text>),
            grid.Column("Cast", "Cast", format: (item) => 
            { 
                string temp = "<div style='text-align: left;color: red;height:120px;" +
                    "width: 175px; padding-right: 1em; overflow: auto; overflow-x:hidden;'>";
                
                var sub = new WebGrid(item.Cast);
                temp += sub.GetHtml(
                    columns:sub.Columns(
                        sub.Column("Name", "Name"),
                        sub.Column("Characters", "Characters", format:(subitem)=>
                            {
                                string temp2 = string.Empty;
                                foreach (var member in subitem.Characters)
                                {
                                    temp2 += member + "<br />";
                                }
                                return new HtmlString(temp2);
                            })
                    ));
                temp += "</div>";
                return new HtmlString(temp);
            })
        )
    )


The main difference when using lambda syntax is that you need to return the HtmlString at the end of the expression. This is the reason I create a string variable named "temp". I then append everything to this variable to create the html string I want to return to the page. I then create a new HtmlString object using the temp variable containing the html as a parameter and return the HtmlString object from the expression.

As before I start out by creating a stylized div to keep the size of the cell reasonable. Since one of the properties of the Cast object is a list I also needed to make sure I set overflow to auto to prevent the rows from getting too tall. When I create the lambda expression I need to specify a parameter to pass into it. This parameter, named item, represents an instance of a Movie object and we can use the Cast object from it as the datasource for the child WebGrid. I created "Name" and "Characters" columns in the sub WebGrid. The "Characters" column contains a list of strings I once again use a lambda expression to format the cells which allows me to use a foreach loop to loop through each character. You could also create an ordered or unordered list, or anything else your imagination can come up with.

And the finished results...

Attached Image

Is This A Good Question/Topic? 1
  • +

Replies To: MVC 3 WebGrid inside a WebGrid

#2 Asusultra  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 7
  • View blog
  • Posts: 39
  • Joined: 24-March 09

Posted 20 May 2011 - 09:52 PM

I just got a task assigned to me that requires something very much like this. Thank you for the tutorial!
Was This Post Helpful? 0
  • +
  • -

#3 Nakor  Icon User is offline

  • Professional Lurker
  • member icon

Reputation: 444
  • View blog
  • Posts: 1,492
  • Joined: 28-April 09

Posted 20 May 2011 - 11:14 PM

No problem, hope it helps :)
Was This Post Helpful? 0
  • +
  • -

#4 skabearbasy  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 26-January 12

Posted 26 January 2012 - 03:03 AM

This article will play you some tips when using the internet to totaly free adult dating sites
black women adult dating
women dating an older man
free adult dating delray
adult dating charlottesville va free
find a date. Dating is like anything else, if you are not ready-made it shows and that is the form affair you want. So lets sick with down to the tips of Matured Dating Online Service's. Many are tense around pronouncement a swain with the commandeer of the internet. The anything else time you demand a Matured Dating Online Rite it can be a speck boldness wracking, but remit it is not difficult. Being perturbed is a good and online dating service for adult
adult dating powered by phpbb
adult sex dating in south dakota
adult dating scotland
adult dating knoxville tn
common retaliation, this shows that you are true and a real person. You thirst for to manipulate emotions or else you may not ever be skilful to descry love. So moderate, receipts a fervent breeze and log into the Of age Dating Online Service.
Was This Post Helpful? 0
  • +
  • -

#5 aramirez  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 20-March 12

Posted 29 March 2012 - 05:19 PM

Hello, thank you for the article!, I'm a newbie, could somebody explain how to create a border in the grid?




how to create a bootable CD
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1