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

为君一笑 提交于 2019-12-03 14:03:31

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"}));

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

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));
        }
    }
}
patridge

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(...))%>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!