Change ordering in MVC3 Index view
Would like to have clickable column titles eg click on TagCode once and it orders by that, and again it reverses. Same for Number.
Using MVC3/Razor and LightSpeed (ORM).
I know that a grid eg http://mvccontrib.codeplex.com/ may be the way forward. But as I don't need paging or filtering, I'd like to keep it simple for now.
Problem Is there a simple example of开发者_如何学Python code (maybe with an up/down icon) that would help?
@Dave
Sorry, I missed your main point in my first answer
If you want to implement sorting using pure MVC3,
I can do that with following steps
- list action method passing sortcolumn and order info to viewpage via ViewBag
- Html Helper method to build actionlink with column ordering display
- list viewpage calling the helper method
I uploaded source code here
List action method
public ActionResult Index(string sortColumn, bool? asc)
{
if (string.IsNullOrWhiteSpace(sortColumn))
sortColumn = "Number";
asc = asc ?? true;
SortDirection sortDirection = asc == true ? SortDirection.Ascending : SortDirection.Descending;
var query = _service.GetTags().OrderBy(sortColumn, sortDirection);
return View(query);
}
Html helper method
public static MvcHtmlString ActionLinkWithColumnOrder(this HtmlHelper helper,
string columnName,string action,string currentColumn,bool currentOrder)
{
object routeValues;
object htmlAttributes = null;
if (columnName == currentColumn)
{
routeValues = new { sortColumn = columnName, asc = !currentOrder };
htmlAttributes = new { @class = currentOrder ? "sort_asc" : "sort_desc" };
}
else
{
routeValues = new { sortColumn = columnName };
}
return helper.ActionLink(columnName, action, routeValues, htmlAttributes);
}
List View page
...
@Html.ActionLinkWithColumnOrder("TagCode", "Index", (string)ViewBag.sortColumn, (bool)ViewBag.asc)
...
@Html.ActionLinkWithColumnOrder("Number", "Index", (string)ViewBag.sortColumn, (bool)ViewBag.asc)
Happy Mvcing!
Sangsu PARK (http://supremeware.blogspot.com)
@Dave
How about using mvccontribgrid with ordering only as follows:
IMO, Using mvccontribgrid may bring more simple code. This is controller code for example
public class HomeController : Controller
{
private AlbumService _service;
public HomeController()
{
_service = new AlbumService();
}
public ActionResult Index(GridSortOptions gridSortOptions)
{
var vm = new ViewModel<Album>()
{
DefaultSort = "AlbumId",
GridSortOptions = gridSortOptions,
List = _service.GetAlbums()
.OrderBy(gridSortOptions.Column, gridSortOptions.Direction),
};
return View(vm);
}
public ActionResult Details(int id)
{
var album = _service.GetAlbum(id);
ViewBag.RouteDicForList = Request.QueryString.ToRouteDic();
return View(album);
}
}
I attached simple sort function source code here with simple service & EF4.
Also, I posted full featured mvccontrib grid filtering & paging article here.
精彩评论