How do I generate a URL outside of a controller in ASP.NET MVC?

房东的猫 提交于 2019-12-09 08:01:50

问题


How do I generate a URL pointing to a controller action from a helper method outside of the controller?


回答1:


Pass UrlHelper to your helper function and then you could do the following:

public SomeReturnType MyHelper(UrlHelper url, // your other parameters)
{
   // Your other code

   var myUrl =  url.Action("action", "controller");

  // code that consumes your url
}



回答2:


You could use the following if you have access to the HttpContext:

var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);



回答3:


Using L01NL's answer, it might be important to note that Action method will also get current parameter if one is provided. E.g:

editing project with id = 100 Url is http://hostname/Project/Edit/100

urlHelper.Action("Edit", "Project") returns http://hostname/Project/Edit/100

while urlHelper.Action("Edit", "Project", new { id = (int?) null }); returns http://hostname/Project/Edit




回答4:


Since you probably want to use the method in a View, you should use the Url property of the view. It is of type UrlHelper, which allows you to do

<%: Url.Action("TheAction", "TheController") %>

If you want to avoid that kind of string references in your views, you could write extension methods on UrlHelper that creates it for you:

public static class UrlHelperExtensions
{
    public static string UrlToTheControllerAction(this UrlHelper helper)
    {
        return helper.Action("TheAction", "TheController");
    }
}

which would be used like so:

<%: Url.UrlToTheControllerTheAction() %>


来源:https://stackoverflow.com/questions/4907540/how-do-i-generate-a-url-outside-of-a-controller-in-asp-net-mvc

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