Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Query string parameters with no values in ASP.NET

I am trying to set up a page that has two behaviors. I'm separating them by URL: One behavior is accessed via /some-controller/some-action, the other is via /some-controller/some-action?customize.

It doesn't look like the Request.QueryString object contains anything, though, when I visit the second URL...I mean, the keys collection has one element in it, but it's null, not 'customize'. Anyone have any ideas about this or how to enable this. I'd like to avoid manually parsing the query string at all costs :).

like image 326
Brad Heller Avatar asked Jun 28 '10 06:06

Brad Heller


People also ask

Can query parameters be empty?

Yes, it is valid. If one simply want to check if the parameter exists or not, this is one way to do so.

How do you pass parameters in query string?

To pass in parameter values, simply append them to the query string at the end of the base URL. In the above example, the view parameter script name is viewParameter1.


1 Answers

Keyless Parameters

John Sherman's answer is only technically correct. Query parameters without values are not supported, but query values without keys are supported.

In other words, "/some-controller/some-action?customize" is considered to be a URL with one query parameter whose value is "customize", and which has no key (i.e. a key of null).

Retrieving

To retrieve all such query parameters you use Request.QueryString.GetValues(null) to retrieve them as an array of strings, or you can use Request.QueryString[null] to get them as a single comma delimited string.

Empty Parameters

An empty parameter (as occurs in "?foo=bar&&spam=eggs"), will show up as a value of string.Empty with a key of null, as does a trailing "&".

The rather unusal query string "?&", for example, will show up as two values of string.Empty, both having a key of null.

The Empty Query String

There is one edge case which does not fit the pattern. That is the empy but present query string (e.g. "/some-controller/some-action?"). Based on the pattern previously shown it would have one value, namely string.Empty with a key of null. However, in reality it will have no values.

like image 137
Kevin Cathcart Avatar answered Sep 23 '22 00:09

Kevin Cathcart