I have the following structure:
Model
public class EventEntry : LogEntry
{
public EventType Type { get; set; }
public string Source { get; set; }
}
public enum EventType : int
{
Information = 1,
Warning = 2,
Error = 3
}
View
<div id="grid">
@{
var grid = new WebGrid(canPage: true, rowsPerPage: Ctrl.PageSize, canSort: true, ajaxUpdateContainerId: "grid");
grid.Bind(Model.Events, rowCount: Model.TotalRecords, autoSortAndPage: false);
grid.Pager(WebGridPagerModes.All);
@grid.GetHtml(htmlAttributes: new { id="grid" },
columns: grid.Columns(
grid.Column("Type"),
grid.Column("Source"));
}
</div>
Controller
public ActionResult Index(int? page, string sort, string sortdir) {...}
When I click on "Source" column that is of type string, the sordir will change from "ASC" to "DESC" but when I try the same thing on the "Type" column sordir will always return "ASC".
The current accepted answer is not the answer to your problem.
It appears that enums are not sorted when you do not mention the columnname in the bind operation. I fixed this by providing all the required column names when binding my model to the webgrid. The UserType property is an enumeration in this example.
var webgrid = new WebGrid(rowsPerPage: 25);
webgrid.Bind(Model, new[] { "FirstName", "MiddleName", "SurName", "UserType" });
var columns = webgrid.Columns(
webgrid.Column("FirstName", "Voornaam"),
webgrid.Column("MiddleName", "Tussenvoegsels"),
webgrid.Column("SurName", "Achternaam"),
webgrid.Column("UserType", "Type gebruiker"),
);
So I reckon that the sorting will work without changing your controller if you implement to following code:
<div id="grid">
@{
var grid = new WebGrid(canPage: true, rowsPerPage: Ctrl.PageSize, canSort: true, ajaxUpdateContainerId: "grid");
grid.Bind(Model.Events, new[] { "Type", "Source" }, rowCount: Model.TotalRecords, autoSortAndPage: false);
grid.Pager(WebGridPagerModes.All);
@grid.GetHtml(htmlAttributes: new { id="grid" },
columns: grid.Columns(
grid.Column("Type"),
grid.Column("Source"));
}
</div>
Try setting the Grid.SortColumn
with the last sorted column.
Controller code
ViewData["lastsortedcol"] = Request["sort"];
View code.
var grid = new WebGrid();
grid.Bind(source: userItems.PagedSet, rowCount: userItemsForSale.TotalCount,autoSortAndPage:false);
grid.SortColumn = (string)ViewData["lastsortedcol"] ;
Response.Write(grid.GetHtml(
columns: grid.Columns
(
grid.Column(columnName: "ItemName", header: "ItemName", format: (item) => Html.Label(((UserItemForSale)item.Value).ItemDetails.Name)),
grid.Column(columnName: "Quantity", header: "Quantity", format: (item) => Html.Label(((UserItemForSale)item.Value).Qty + ""))
)
));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With