我正在使用MvcContrib Grid的Sort方法来生成排序链接,例如
<%= Html.Grid(Model).AutoGenerateColumns().Sort((GridSortOptions)ViewData["sort"]) %>
我需要更改sort方法生成的默认控制器/操作。例如,
defaultControllerName/defaultActionName/?Column=ProductId&Direction=Ascending
会改为
customControllerName/customActionName/?Column=ProductId&Direction=Ascending
我无法在MVCcontribution类中找到允许我自定义链接的任何现有方法。我很感激有关如何改变默认链接的任何指示,因为我仍然是一个MVC / C#新手。
答案 0 :(得分:1)
这不是一件容易的事。您将需要一个自定义网格渲染器来实现此目的并覆盖RenderHeaderText方法:
public class MyHtmlTableGridRenderer<T> : HtmlTableGridRenderer<T> where TViewModel : class
{
protected override void RenderHeaderText(GridColumn<TViewModel> column)
{
if (IsSortingEnabled && column.Sortable)
{
// TODO: generate a custom link here based on the sorting options
string text = ...
base.RenderText(text);
}
else
{
RenderText(column.DisplayName);
}
}
}
然后指定网格应使用此渲染器:
.RenderUsing(new MyHtmlTableGridRenderer<Employee>())
答案 1 :(得分:0)
我想提供一个完整的工作示例:
public class SortableHtmlTableGridRenderer<T> : HtmlTableGridRenderer<T> where T : class
{
readonly string _action;
readonly string _controllerName;
public SortableHtmlTableGridRenderer(string action, string controllerName)
{
_action = action;
_controllerName = controllerName;
}
protected override void RenderHeaderText(GridColumn<T> column)
{
if (IsSortingEnabled && column.Sortable)
{
string sortColumnName = GenerateSortColumnName(column);
bool isSortedByThisColumn = GridModel.SortOptions.Column == sortColumnName;
var sortOptions = new GridSortOptions
{
Column = sortColumnName
};
if (isSortedByThisColumn)
{
sortOptions.Direction = (GridModel.SortOptions.Direction == SortDirection.Ascending)
? SortDirection.Descending
: SortDirection.Ascending;
}
else //default sort order
{
sortOptions.Direction = column.InitialDirection ?? GridModel.SortOptions.Direction;
}
var routeValues = HtmlHelper.AnonymousObjectToHtmlAttributes(new {sortOptions.Column, sortOptions.Direction });
var text = HtmlHelper.GenerateLink(Context.RequestContext, RouteTable.Routes, column.DisplayName, null, _action, _controllerName, routeValues, null);
RenderText(text);
}
else
{
RenderText(column.DisplayName);
}
}
}
用法:
.RenderUsing(new SortableHtmlTableGridRenderer<YourModelType>("Search", "Search"))