Asp.net-mvc – Call UrlHelper in models in ASP.NET MVC

asp.net-mvcurlhelper

I need to generate some URLs in a model in ASP.NET MVC. I'd like to call something like UrlHelper.Action() which uses the routes to generate the URL. I don't mind filling the usual blanks, like the hostname, scheme and so on.

Is there any method I can call for that? Is there a way to construct an UrlHelper?

Best Answer

Helpful tip, in any ASP.NET application, you can get a reference of the current HttpContext

HttpContext.Current

which is derived from System.Web. Therefore, the following will work anywhere in an ASP.NET MVC application:

UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext);
url.Action("ContactUs"); // Will output the proper link according to routing info

Example:

public class MyModel
{
    public int ID { get; private set; }
    public string Link
    {
        get
        {
            UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext);
            return url.Action("ViewAction", "MyModelController", new { id = this.ID });
        }
    }

    public MyModel(int id)
    {
        this.ID = id;
    }
}

Calling the Link property on a created MyModel object will return the valid Url to view the Model based on the routing in Global.asax