Thursday, 5 July 2007

SubSonic GridView and ObjectDataSource

I have been experimenting with using SubSonic to convert my commentaries web page from PHP to ASP.NET. This is a very simple web page allows you to look at a list of books, sort them and filter them - nothing complicated. And Subsonic offers an automatic DAL layer which requires you simply to point it at your database and let it create the classes for you.

So one of the first tasks I approached was to work out how to get a asp:GridView to work with my SubSonic data objects. My first approach was to do it in code, with the following code in my Page_Load event:

CommentaryController c = new CommentaryController();
CommentaryCollection cc = c.FetchAll();            
gridCommentaries.DataSource = cc;

This worked nicely, but I wanted to know if there was a better way using the asp:ObjectDataSource. The SubSonic documentation is still a little sparse in this area, but I eventually worked out the syntax. You use the auto-generated "Controller" object that SubSonic has made for your table:

<asp:ObjectDataSource ID="odsCommentaries" runat="server" 
SelectMethod="FetchAll" />

Simple when you know how! Now you just need to set the DataSourceID of the grid. Paging can be also turned on, but sorting doesn't. I'll perhaps post again when I have gone a bit deeper.


Robert said...

Hi Mark, Xmas is traditionally my learning time, I got started with thanks to VWD Express in Xmas 2005 and this year I'm desperate to find a way thru the DAL/BLL, ORM, Table adapter, classes maze and just downloaded SubSonic. I have my gridview paging, editing and deleting thanks to SubSonic controller classes and objectdatasource but not sorting and wondered if you found a solution to sorting with SubSonic? The other thing I'm working on is simple joins as I use lookup tables with int key and text lookup value and like to show the text value in a label control in item template but show a dropdown list in edit template so I need to join my main table to lookup tables. How do you do that in SubSonic?

Matt said...

Could you explain your code a little more, specifically TypeName="CommentariesDB.CommentaryController"
SubSonic uses the connectionstring to connect to the DB so what does the syntax of TypeName point to? I hope I haven't been to vague.

Mark H said...

Hi Matt,
CommentariesDB.CommentaryController is one of the automatically generated objects that SubSonic creates for you. CommenantariesDB is the namespace and CommentaryController is the type name. It has a FetchAll member function that the object data source can use to get all its data.

Anonymous said...

salut j'ai le même problème de tri est ce que vous avez trouvez une solution , merci