My ASP.NET MVC application adds a route named "Asset" to the RouteTable
, and I have a static method.
This static method needs to be able to generate the URL to the "Asset" route of the application.
How can I do this?
The one restriction on action method is that they have to be instance method, so they cannot be static methods. Also there is no return value restrictions. So you can return the string, integer, etc.
Action(String, String, Object, String) Generates a fully qualified URL to an action method by using the specified action name, controller name, route values, and protocol to use.
The helper class:
public static class UrlHelper
{
private static System.Web.Mvc.UrlHelper _urlHelper;
public static System.Web.Mvc.UrlHelper GetFromContext()
{
if (_urlHelper == null)
{
if (HttpContext.Current == null)
{
throw new HttpException("Current httpcontext is null!");
}
if (!(HttpContext.Current.CurrentHandler is System.Web.Mvc.MvcHandler))
{
throw new HttpException("Type casting is failed!");
}
_urlHelper = new System.Web.Mvc.UrlHelper(((System.Web.Mvc.MvcHandler)HttpContext.Current.CurrentHandler).RequestContext);
}
return _urlHelper;
}
}
The calling:
UrlHelper.GetFromContext().Action("action", "controller");
assuming your code is running in the context of a http request, you can do the following from a static method:
new UrlHelper(HttpContext.Current.Request.RequestContext);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With