Reputation: 8454
Is there a way I can remove null or empty keys from a query string in asp.net MVC? For example I have a page where I filter data on a results table, if I search for John the query string would be redisplayed as:
candidates?FirstName=John&LastName=&Credit=false&Previous=false&Education=&Progress=
and not
candidates?FirstName=John
I looked at URL routing but I wasn't sure if it was something that should be used for cosmetic things like this or if it is possible to achieve what I'm asking using it.
Upvotes: 5
Views: 3452
Reputation: 53125
Maybe use this Querystring Builder - iterate querystrings in the Request.QueryString dictionary and build a new one using the builder (or just string-concat them)?
Upvotes: 0
Reputation: 15901
I sometimes need to work on my route values in partials that are used by variuos views.
Then I usualy access the routeDictionary and change it. The benefit you get is, that there is a good chance that the code will survive changes in the routing and that you can use routeValues in multiple generated URL.
Most people would argue that the best place for this code is not the view. But hopefully you get the idea.
The view code:
RouteValueDictionary routeValues = ViewContext.RouteData.Values;
routeValues.Remove(...);
routeValues.Add(...);
routeValues["Key"] = ...;
<%
using (Html.BeginForm(
Url.RequestContext.RouteData.GetRequiredString("Action"),
Url.RequestContext.RouteData.GetRequiredString("Controller"),
routeValues,
FormMethod.Get))
{ %>
Upvotes: 0
Reputation: 59011
How are you generating that URL? With Routing, if those are meant to be in the query string, it should work fine. We only generate query string parameters for RouteValues that you specify.
One thing I've done in the past is to write my own helper method for specific links where I might pass in an object for route values, but want to clear out the values that I don't need before passing it to the underlying routing API. That worked well for me.
Upvotes: 2
Reputation: 2253
Whatever URL generator, or control you are using would need special logic to strip these unwanted tags from the list. It's not obvious to a generic URL generator or control that Credit=false
is useless -- couldn't it be Credit=true
is the default? Similarly an empty string can mean something. (Also, Lastname=
is different from Lastname
.
Upvotes: 0