MVC3 WebGrid toggling sort direction

With an ASP.NET MVC3 WebGrid how can I setup the column sorting such that clicking on the column heading toggles between ascending sort and then descending sort?

Thanks!

Rob

-------------Problems Reply------------

The underlying problem turned out to be a malformed column. The columnName did not in fact match the actual columnName (it was set to be the header text). This problem was hidden because the format specified a Html.ActionLink.

Changing the column definition such that the columnName was correct (and the header set to the actual header value) corrected the problem.

Note 1: Using Razor Syntax for Markup and C# as ServerSide Code.

Note 2: The basic setup knowledge for Sorting came from Sorting, Filtering, and Paging with the Entity Framework Tutorial but I needed more control and leverage than what they supplied for their simple example.

So...

Here is the End-Result-View View for the Grid

Here is my ServerSide code on the Index Action (so when my page loads) (again, see link above for more background information)

public ViewResult Index(string sortOrder)
{
// Set the defaults
ViewBag.FirstNameSortParam = "First Name desc";
ViewBag.LastNameSortParam = "Last Name desc";
ViewBag.CitySortParam = "City desc";
ViewBag.StateSortParam = "State desc";
ViewBag.DOBSortParam = "DOB desc";

var students = from s in db.Students select s;

switch (sortOrder)
{
case "First Name desc":
students = students.OrderByDescending(s => s.FirstName);
ViewBag.FirstNameSortParam = sortOrder;
break;
case "First Name asc":
students = students.OrderBy(s => s.FirstName);
ViewBag.FirstNameSortParam = sortOrder;
break;
case "Last Name desc":
students = students.OrderByDescending(s => s.LastName);
ViewBag.LastNameSortParam = sortOrder;
break;
case "Last Name asc":
students = students.OrderBy(s => s.LastName);
ViewBag.LastNameSortParam = sortOrder;
break;
case "City desc":
students = students.OrderByDescending(s => s.StudentAddress.City);
ViewBag.CitySortParam = sortOrder;
break;
case "City asc":
students = students.OrderBy(s => s.StudentAddress.City);
ViewBag.CitySortParam = sortOrder;
break;
case "State desc":
students = students.OrderByDescending(s => s.StudentAddress.State);
ViewBag.StateSortParam = sortOrder;
break;
case "State asc":
students = students.OrderBy(s => s.StudentAddress.State);
ViewBag.StateSortParam = sortOrder;
break;
case "DOB desc":
students = students.OrderByDescending(s => s.DOB);
ViewBag.DOBSortParam = sortOrder;
break;
case "DOB asc":
students = students.OrderBy(s => s.DOB);
ViewBag.DOBSortParam = sortOrder;
break;
default:
students = students.OrderByDescending(s => s.StudentID);
break;
}

return View(students.ToList());
}

The first time this runs, of course "sortOrder" will be null. However the pattern below demonstrates how I accomplished toggling of the "Last Name" column. Also, please note that I set my default 1st state to be Descending. Alternatively you could flip-it-around if you want Ascending as the 1st state registered when a user clicks on the link. For my purposes "Descending" works best.

@{
string fnSort = ViewBag.FirstNameSortParam;
string lnSort = ViewBag.LastNameSortParam;
string citySort = ViewBag.CitySortParam;
string stateSort = ViewBag.StateSortParam;
string dobSort = ViewBag.DOBSortParam;
}
<table>
<tr>
<th>
@{
if (fnSort != "First Name desc")
{
fnSort = "First Name desc";
}else{
fnSort = "First Name asc";
}
}
@Html.ActionLink("First Name", "Index", new { sortOrder = fnSort })
</th>
<th>
@{
if (lnSort != "Last Name desc")
{
lnSort = "Last Name desc";
}else{
lnSort = "Last Name asc";
}
}

@Html.ActionLink("Last Name", "Index", new { sortOrder = lnSort })
</th>
<th>
Email
</th>
<th>
Phone Number
</th>
<th>
@{
if (citySort != "City desc")
{
citySort = "City desc";
}else{
citySort = "City asc";
}
}

@Html.ActionLink("City", "Index", new { sortOrder = citySort })
</th>
<th>
@{
if (stateSort != "State desc")
{
stateSort = "State desc";
}else{
stateSort = "State asc";
}
}

@Html.ActionLink("State", "Index", new { sortOrder = stateSort })
</th>
<th>
@{
if (dobSort != "DOB desc")
{
dobSort = "DOB desc";
}else{
dobSort = "DOB asc";
}
}

@Html.ActionLink("DOB", "Index", new { sortOrder = dobSort })
</th>
<th></th>
</tr>

@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
@Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
<td>
@Html.DisplayFor(modelItem => item.PhoneNumber)
</td>
<td>
@Html.DisplayFor(modelItem => item.StudentAddress.City)
</td>
<td>
@Html.DisplayFor(modelItem => item.StudentAddress.State)
</td>
<td>
@Html.DisplayFor(modelItem => item.DOB)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.StudentID }) |
@Html.ActionLink("Details", "Details", new { id=item.StudentID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.StudentID })
</td>
</tr>
}

</table>

That's it... Toggling works now for "Last Name"... now I will implement sort toggling for the other columns as well

Hope this helps. Let me know if you need more assistance! I'm proud to help (if I can)

Cheers!

Category:asp.net mvc 3 Views:0 Time:2011-11-12

Related post

  • MVC3 WebGrid Page/Sort Issue with a CheckBox elsewhere on the page 2011-11-17

    I have a checkbox on my page, created as such: @Html.CheckBoxFor(x => x.MyBoolValue) Beneath that I have a WebGrid with sorting and paging, but on doing this I get a System.InvalidOperationException: The parameter conversion from type 'System.Stri

  • MVC3 WebGrid: When sorting or paging, is there a way to call a javascript method BEFORE the Controller Action method is called? 2011-07-08

    I've been using this link as a reference for developing my WebGrid (http://msdn.microsoft.com/en-us/magazine/hh288075.aspx). Currently what is happening is that my WebGrid is loaded, and I'm able to asynchronously page and sort just fine...no problem

  • ASP.NET MVC3 WebGrid - custom, server-side sorting 2012-04-12

    Is there a way to override default MVC3 WebGrid sorting behavior to call my controller (which will perform server side sorting and return the data) when sort is called? Thanks for any help! --------------Solutions------------- You can pass the server

  • MVC3 Webgrid Paging and Sorting 2011-07-18

    I'm using MVC3 webgrid to display, sort and paginate data. The display is fine, but when I click on a new page or request a sort, it opens the table in a brand new window on it's own? Anybody know why this happens? It is contained within a partial vi

  • Why aren't MVC3 webgrid paging and sorting working? 2011-11-04

    I'm using MVC3 webgrid to display, sort and paginate data. The display is fine, but when I click on a new page or request a sort, nothing is happening. This is the code that I'm using: @if (Model.AdsList != null) { WebGrid adGrid = new WebGrid(Model.

  • How can I format a MVC3 WebGrid date column for local timezone? 2012-03-06

    My datetime values are stored as UTC in the database. I want to display them in the local timezone using the standard MVC3 WebGrid control, but don't have a clue how to do that or where to look for the answer. My current code looks like this: grid.Co

  • Linq Sort Direction From String 2009-09-29

    I am trying to sort a set of Users. I have access to the sorting property and direction (asc, desc). My current order by query is below. But as you can see it doesn't account for the sort direction. How do can I build this expression without having t

  • Telerik MVC Grid: Setting the Default Sorting direction 2010-07-19

    Is there a way to specify the default sorting direction for columns in a Telerik MVC Grid? example: click on column 'Date' and it sorts descending, click on column 'Name' and it sorts ascending --------------Solutions------------- I do not think ther

  • How to add arrow to each WPF listview column to indicate sort direction 2010-07-29

    I have a gridview ...with multiple columns. If I click on one column, it sorts the gridview based on that column values. I like to add an arrow in that "clicked" column header(when user clicks) to show that "this particular column is clicked and this

  • How to hide header on MVC3 WebGrid 2011-01-17

    Is there some easy way to hide header for MVC3 WebGrid extension? Something like var grid = new WebGrid(Model, canSort:false, canPage:false, showHeader:false); I can probably set css style for header that will cause header not showing, though I'd rat

  • DataGridView/IBindingList sort direction problems 2011-01-18

    I have a DataGridView bound to a BindingSource, which is in turn bound to a custom implementation of IBindingList that provides sorting. My DataGridView columns are set to support Automatic sorting. The behavior I would expect is that the first time

  • MVC3 WebGrid Formatting or Styling Column Headers 2011-02-01

    I'm using the new MVC3 WebGrid. So far so good, just having issues styling/formatting the column headers. The best I've got is a workaround that applies the same css class from the first row of the WebGrid to the table header. var headerCells = $("#g

  • Server side paging for MVC3 Webgrid 2011-06-21

    I have looked at a number of examples (e.g. http://www.dotnetcurry.com/ShowArticle.aspx?ID=618 and http://msdn.microsoft.com/en-us/magazine/gg650669.aspx) but it seems very manual and convoluted. The reason I would like to use the WebGrid is that the

  • Based on Model Column Value(true/False) in MVC3 Webgrid , How can Add a Link as column in diplaying the rows 2011-07-18

    I am using MVC3 Webgrid. I have model which has column of type bool. Based on the Value of this coulumn I need to render a coulmn , with hyper link. If the bool column value is true then I have to render Record, else Edit. Could you kindly give the s

  • How can I change the default sort direction when clicking a column in a GridView? 2011-08-24

    How can I change the default sort direction when clicking a column in an ASP.NET GridView? I would like it so that when a new column is clicked, it sorts in DESC order by default instead of ASC. protected void OnGridViewSorting(object sender, GridVie

  • Gridview Control Sorting Direction 2011-10-06

    The default sorting order on the gridview control is ascending first, then descending. Now below I have code to change that around. So far so good. But when I click on another column again, it sets the sort direction to ascending again. It alternates

  • Does MVC3 WebGrid support horizontal scrollbars? 2011-10-21

    I have a record set that is quite wide (about 25-30 cols)...does MVC3 WebGrid support horizontal scrollbars (or can I house the grid in a html tag/control)? --------------Solutions------------- Never realised about the WebGrid, so had to play with it

  • ASP .NET MVC3 WebGrid footer 2011-10-26

    I really cannot find any good solution to realize ASP .NET MVC3 WebGrid footer which has some total values... Any clue how to do it? Thank you! --------------Solutions------------- I assume best approach is to calculate total value and pass it in mod

  • Sort direction ASC/DESC not being handled using PDO (MySQL) 2011-12-12

    I am trying to retrieve a set of of results by column using PDO (mysql). For some reason, the ASC/DESC mysql keywords aren't being processed. Example Query: "SELECT itemid, itemgroup, added_date FROM items WHERE itemgroup = 'book' ORDER BY added_date

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.175 (s). 11 q(s)