Best way to add filter to URL in .NET MVC

I will try to make this as concise as possible.

  • The web page contains a table that allows you to filter and sort
  • Changes to filtering and sorting should be reflected in the URL so that the user can add bookmarks or share filters.

The question is: what is an effective agreement to allow sorting and filtering syntax to be part of the URL and easily interpret / use it on the server without having to write a bunch of custom code that interprets it?

I did some research, and I had to deal with UD OData conventions, and I like the way they do it. http://www.odata.org/developers/protocols/uri-conventions

More research shows that the MVC 4 web API allows you to use this convention by returning IQueryable. It looks fantastic, except for one part ... I am not implementing a RESTful API at the moment and that it all seems to work. So, how can I use something like OData and still return a View or PartialView? Is there something that will parse the OData URI convention into a C # object?

If anyone has an understanding of this problem or suggestions, I’m all ears.

+6
source share
2 answers

Regarding part of your URL convention, I think you answered your question with OData. As for getting this data in a C # object, I would use the following approach:

Use an action filter to interpolate URL parameters and parse them into a C # object. In your action filter, add the URL parameters to the route data and the C # object will be available in your action.

ASP.NET MVC pass object from custom action filter to action

Look at the Telerik MVC grid, they use the GridAction action filter, which does pretty much what you ask for.

0
source

I would look at the user binding of the model. A good review can be found here: http://weblogs.asp.net/nmarun/archive/2010/02/25/asp-net-mvc-model-binding.aspx

It is commonly used for POST requests with forms, but there is no reason why you cannot use it for GET requests.

Basically, your approach should be as follows:

  • Create a new Model class with filter / sort options as properties:

    public class TableParameters { public string TableFilter { get; set; } } 
  • In your Controller action, add the model as a parameter

      public ActionResult TableAction(TableParameters parameters) { /* Action logic */ } 
  • Set your parameters in the URL by saying:

      /Controller/TableAction?TableFilter=[your-filter-string] 

The parameter object in your action will have a property populated with the value from the query string.

0
source

Source: https://habr.com/ru/post/911458/


All Articles