Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maintaining the query string in ASP.Net MVC

Tags:

c#

asp.net-mvc

Just beginning my journey in ASP.Net MVC and I have a query about something before I dig myself in too deep.

I have a table, which is paged, and I have 2 controls above the table:

  • Dropdown that defines order of the results and apply button next to it
  • Textbox that defines a filter and apply button next to it

What I need to achieve is that if the user changes the order or adds a filter I fire of an AJAX call to my action like such: /Membership/Users?sort=value&filter=value&page=pagenumber. So my controller action is:

   // GET Membership/Users?sort=&filter=&page=
   public ActionResult Users(string sort, string filter, string page)

So I have 3 questions:

  • Is this the correct approach?
  • What would be the best way to ensure that the query string is maintained, bearing in mind that the action will nearly always be called by Jquery/Ajax functions?
  • If I wanted to link directly to this action passing the arguments would I need to hard-code the querystring?

Thanks

like image 948
Mantorok Avatar asked Dec 15 '25 11:12

Mantorok


1 Answers

You could define a new route in the format Membership/Users/{sort}/{filter}/{page}.

routes.MapRoute(
        "MembershipList",                                              
        "Membership/Users/{sort}/{filter}/{page}",             
        new { controller = "Membership", action = "Users", sort = "", filter = "", page = "" }
    );

However, if the parameters are optional then I would suggest you leave it as is and don't define a route.

As you are passing through strings then they will simply be passed as null if for some reason no query strings are passed, your action should handle this and still render a view.

like image 165
David Neale Avatar answered Dec 17 '25 02:12

David Neale



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!