Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 3 Reusable Table Display Template with Razor

Is there a good way for creating a tabular display template in ASP.NET MVC3 with the new Razor syntax?

In ASP.NET MVC 2 Phil Haack was blogging about tabular display templates. Is there a better approach in ASP.NET MVC3?

EDIT:

Is it also possible to render the grid on the basis of the model meta data? So I do not want to manually define the columns with the WebGrid API but with model meta data. The problem I see is that you everytime have to define the table by hand using the WebGrid API. I want to have the possibility to have one kind of table that is reusable!

Edit: So is there any good practice for creating grids using model meta data?

like image 471
Rookian Avatar asked Mar 02 '11 20:03

Rookian


2 Answers

You can use the new WebGrid in MVC3:

@{
    var grid = new WebGrid(Model);
    @grid.GetHtml();
}

And you can use jQuery tabs: http://jqueryui.com/demos/tabs, to create tab pages.

Sorry if I am misunderstood your question.

like image 108
Kalman Speier Avatar answered Sep 28 '22 09:09

Kalman Speier


I haven't used it much but from my understanding you must first setup MVC 3's WebGrid before using it. And you don't want to setup the table in the view but instead do it using model attributes.

If I where to do that I would do the following:

  • Create my custom attributes with which I would decorate my model to define which properties are columns, what labels will be used for column header and anything else you want to configure.

  • I will make a static class with a static method that takes in your model instance, uses reflection to read the properties and your custom attributes and from there it will spit out the WebGrid for you to use in your view.

That's the how but I'll tell you why I wouldn't do this: in MVC you decorate your model for things like validation and that is great and declarative. But when you define a grid, this is a very view specific thing. Sure you may be using the ViewModels which are view specific but I don't think table layout configuration belongs in the model. The way WebGrid or Telerik's Grid before it work is already nicely declarative already.

I short WebGrid and Telerik's Grid are already using best practices by offering declarative, fluent interfaces to define table structure and behaviour. Each table is different so it makes sense you are defining each table. You say "by hand" but this is far from the case as the Grids are doing all the dirty work for you, you are just telling it what you want (declarative programming).

like image 43
Fabian Nicollier Avatar answered Sep 28 '22 10:09

Fabian Nicollier