Monday, January 31, 2011

Sort indicator in System.Web.Helpers.WebGrid

ASP.NET MVC 3 has a new long expected native class System.Web.Helpers.WebGrid which is highly customizable and could be used in a number of different scenarios. Among other the grid is able to automatically sort data by selected column.

I would like to show how to add a sort indicator near the column title. It's not too difficult, but as I know, can't be done by configuring WebGrid itself. This sample is using new Razor view engine.

This markup


renders to:


As you can see column titles are linked to the same page but these links now have two extra parameters sort and sortdir which are considered by WebGrid during rendering process. These parameters are mapped to SortColumn and SortDirection properties respectively. Thus we can check if data is sorted, determine selected column using jQuery selector and add a little triangle to it's title:


The indicator will look like this:


This sample of course could be expanded for real world usage.

Thursday, December 16, 2010

Randomize with LINQ

Once my colleague showed me a nice way to randomize table records:



I tried to use this trick with LINQ:



but unfortunately it doesn't work. The cities weren't randomized at all. It turned out what during SQL query generation Guid.NewGuid() was treated as a constant and was ignored as the same for all records.

So the right way in this case is to call AsEnumerable() first:



Another interesting thing is what enumerating ci now gives different results every time, so this code might give wrong result:



other might contain first element anyway because records are randomized during second use of ci variable. To avoid this side effect we need to "freeze" elements with ToList():



After that the result will be as expected.