ASP.NET MVC "Grid View" made in Home
October 1st, 2008
The first time that I saw ASP.NET MVC, I was at a Microsoft Tech-night, the speaker was my admired co-worker, Edgardo Rossetto, and I felt in love with the framework. It brought me many memories about my ASP 3.0 developer time.
ASP.NET MVC is not a replace for ASP.NET Web Forms model, is just another choice, and I really like, because I’m a patterns lover and, as you can imagine, ASP.NET MVC is based on the famous MVC Pattern, but also is great because enable easy Test-Driven Development, and every single action is easy mapped to a REST-friendly URL.
So, given that, I want to share with you a little home-made project, my own ASP.NET MVC Grid View.
Before you feel so excited, it do not support paging and sorting (yet), but you can easily add these features in your controller. Right now, it supports simply "Data Source" (any IEnumarable object), extensible "Column Definitions" and CSS Styles.
How to use it?
This grid View is basically composed by a Web Control, and a set of "model" classes.
The data (DataSource, ColumnDefinitions, CSS Styles, etc…) is given to the WebControl as ViewData. Let’s see that…
Mock Data (Just a method that returns a list of users):
Controller example code (DataSource & Column Definitions at Controller):
View example code:
The result:
How does it work?
The method in change of render the value of each field is place in GridColumnDefinition base class. As you can imagine, it’s based on reflection, using the value of PropertyName to find the value to render.
This is the magic method:
Here we’ve something cool; this method is also based on Template Method Pattern, to allow formatting the value before render, so you can write your own implementation of the FormatValue method.
I’ve written three as example…
This is the GridImageColumn implementation of FormatValue, to render an HTML image with the value…
Perhaps an "Action" column definition can be implemented giving as value the Id; it’s free to your imagination!
You can download the source code here.
Leave a Reply