Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Built in method to encode ampersands in urls returned from Url.Action?

I am using Url.Action to generate a URL with two query parameters on a site that has a doctype of XHTML strict.

Url.Action("ActionName", "ControllerName", new { paramA="1" paramB="2" })

generates:

/ControllerName/ActionName/?paramA=1&paramB=2

but I need it to generate the url with the ampersand escaped:

/ControllerName/ActionName/?paramA=1&paramB=2

The fact that Url.Action is returning the URL with the ampersand not escaped breaks my HTML validation. My current solution is to just manually replace ampersand in the URL returned from Url.Action with an escaped ampersand. Is there a built in or better solution to this problem?

like image 999
Blegger Avatar asked May 24 '10 17:05

Blegger


People also ask

How do I encode an ampersand in a URL?

For example, to encode a URL with an ampersand character, use %26. However, in HTML, use either & or &, both of which would write out the ampersand in the HTML page.

Can you use an ampersand in a URL?

No. Unfortunately you can't use ampersands (&) as part of your domain name. Characters that you can use in your domain name include letters, numbers and hyphens.


2 Answers

This worked for me:

Html.Raw(Url.Action("ActionName", "ControllerName", new { paramA="1" paramB="2" }))
like image 61
Kyle Avatar answered Oct 15 '22 04:10

Kyle


Any reason you can't use Server.HtmlEncode()

string EncodedUrl = Server.HtmlEncode(Url.Action("Action", "Controller", new {paramA = "1", paramB = "2"}));

http://msdn.microsoft.com/en-us/library/w3te6wfz.aspx

like image 30
dbugger Avatar answered Oct 15 '22 03:10

dbugger