Search code examples
asp.net-mvcinvalid-url

Why is this query string invalid?


In my asp.net mvc page I create a link that renders as followed:

http://localhost:3035/Formula/OverView?colorId=349405&paintCode=744&name=BRILLANT%20SILVER&formulaId=570230

According to the W3C validator, this is not correct and it errors after the first ampersand. It complains about the & not being encoded and the entity &p not recognised etc.

AFAIK the & shouldn't be encoded because it is a separator for the key value pair.

For those who care: I send these pars as querystring and not as "/" seperated values because there is no decent way of passing on optional parameters that I know of.

To put all the bits together:

  • an anchor (<a>) tag's href attribute needs an encoded value
  • & encodes to &amp;
  • to encode an '&' when it is part of your parameter's value, use %26

Wouldn't encoding the ampersand into & make it part of my parameter's value? I need it to seperate the second variable from the first

Indeed, by encoding my href value, I do get rid of the errors. What I'm wondering now however is what to do if for example my colorId would be "123&456", where the ampersand is part of the value. Since the separator has to be encoded, what to do with encoded ampersands. Do they need to be encoded twice so to speak?

So to get the url:

www.mySite.com/search?query=123&amp;456&page=1

What should my href value be?

Also, I think I'm about the first person in the world to care about this.. go check the www and count the pages that get their query string validated in the W3C validator..


Solution

  • All HTML attributes need to use character entities. You only don't need to change & into &amp; within script blocks.

    <a href="http://localhost:3035/Formula/OverView?colorId=349405&amp;paintCode=744&amp;name=BRILLANT%20SILVER&amp;formulaId=570230">Whatever</a>
    

    Anywhere in an HTML document that you want an & to display directly next to something other than whitespace, you need to use the character entity &amp;. If it is part of an attribute, the &amp; will work as though it was an &. If the document is XHTML, you need to use character entities everywhere, even if you don't have something immediately next to the &. You can also use other character entities as part of attributes to treat them as though they were the actual characters.

    If you want to use an ampersand as part of a URL in a way other than as a separator for parameters, you should use %26.

    As an example...

    <a href="http://localhost/Hello?name=Bob&amp;text=you%20%26%20me%20&quot;forever&quot;">Hello</a>
    

    Would send the user to http://localhost/Hello, with name=Bob and text=you & me "forever".