Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change WebGrid action for getting data (.NET MVC3)

I have a Partial View that renders WebGrid. My controller looks like

public ActionResult Index()
{
    return View();
}
public ActionResult GetUserList(int? page, string sort, string sortdir)
{
    var model = UserModel.getList(page,sort,sortdir);
    return PartialView("_UserList",model);
}

Index.cshtml :
....
@Html.Action("GetUserList")

The problem is that every time I click on grid navigation or sort links it calls Index method. How can I make Webgrid to execute a different action (GetUserList in this case)? I'm sure I can prepend GetUserList to all links in grid using jquery, but I believe it should be a better way.
It's also possible that what I'm doing is completely wrong, so thanks for your suggestions.

like image 784
a1ex07 Avatar asked May 11 '11 17:05

a1ex07


1 Answers

After lot of monkeying around and digging (and even fiddling with Reflector with WebGrid's source code), I came to the conclusion that with WebGrid, you cannot control/change the Header link action.

To create the header link URL, the path is taken from HttpContext.Request.Path, so there is no way to customize it to point to a different route.

One very ugly hack would be to tap into to jQuery Ajax's events (since the header link uses jQuery.load to sort) and overwrite the URL:

<a href="#" onclick="$('#myGrid').load('/?sort=AlbumId&amp;sortdir=ASC&amp;__=634486582282704242 #myGrid');">Album Id</a>

Better solution would be to use:

  • Telerik Grid which lets you specify custom routes and also offers much more flexibility in rendering your layout
  • or MvcContrib Grid (not sure if this lets you modify header links but definitely offers more flexibility than WebGrid)
like image 196
Mrchief Avatar answered Nov 15 '22 05:11

Mrchief