views:

143

answers:

2

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?

+1  A: 

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

dbugger
I was hoping for some configuration setting that would allow Url.Action to automatically do this for me, but this is definitely better than just manually replacing the ampersand.
Blegger
A: 

I ended up just creating extensions for Url.Action called Url.ActionEncoded. The code is as follows:

namespace System.Web.Mvc {
    public static class UrlHelperExtension {
        public static string ActionEncoded(this UrlHelper helper, StpLibrary.RouteObject customLinkObject) {
            return HttpUtility.HtmlEncode(helper.Action(customLinkObject.Action, customLinkObject.Controller, customLinkObject.Routes));
        }
        public static string ActionEncoded(this UrlHelper helper, string action) {
            return HttpUtility.HtmlEncode(helper.Action(action));
        }
        public static string ActionEncoded(this UrlHelper helper, string action, object routeValues) {
            return HttpUtility.HtmlEncode(helper.Action(action, routeValues));
        }
        public static string ActionEncoded(this UrlHelper helper, string action, string controller, object routeValues) {
            return HttpUtility.HtmlEncode(helper.Action(action, controller, routeValues));
        }
    }
}
Blegger