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¶mB=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?
This worked for me:
Html.Raw(Url.Action("ActionName", "ControllerName", new { paramA="1" paramB="2" }))
Any reason you can't use Server.HtmlEncode()
string EncodedUrl = Server.HtmlEncode(Url.Action("Action", "Controller", new {paramA = "1", paramB = "2"}));
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));
}
}
}
You appear to have an issue with the rendering of a URL, not the generation of the URL. A URL can have an unencoded ampersand in it and there are places that may be exactly what you need. The HTML you are embedding it into in this case, though, wants ampersands and various other characters encoded.
While a helper method would save some typing in views, I always find it saves headaches to have the any display encoding done at the last possible moment so I am always working with the genuine string/URL right up until the point I need it manipulated for use in a particular output format. If you put the helper extension from your answer in HtmlHelper, you will be less tempted to prematurely encode your URL before it is actually needed.
To put it raw in HTML:
// with MVC3 auto-encoding goodness
<%:Url.Action(...)%>
// old-school MVC
<%=Html.Encode(Url.Action(...))%>
To put it in an anchor/src attribute directly in a view, you could probably get away with Html.Encode
or the less-strict option:
<%=Html.AttributeEncode(Url.Action(...))%>
来源:https://stackoverflow.com/questions/2898855/built-in-method-to-encode-ampersands-in-urls-returned-from-url-action