Inside o开发者_JAVA技巧f a View can I get a full route information to an action?
If I have an action called DoThis in a controller MyController. Can I get to a path of "/MyController/DoThis/"
?
You mean like using the Action method on the Url helper:
<%= Url.Action("DoThis", "MyController") %>
or in Razor:
@Url.Action("DoThis", "MyController")
which will give you a relative url (/MyController/DoThis
).
And if you wanted to get an absolute url (http://localhost:8385/MyController/DoThis
):
<%= Url.Action("DoThis", "MyController", null, Request.Url.Scheme, null) %>
Some days ago, I wrote a blog post about that very topic (see How to build absolute action URLs using the UrlHelper class). As Darin Dimitrov mentioned: UrlHelper.Action
will generate absolute URLs if the protocol
parameter is specified explicitly.
However, I suggest to write a custom extension method for the sake of readability:
/// <summary>
/// Generates a fully qualified URL to an action method by using
/// the specified action name, controller name and route values.
/// </summary>
/// <param name="url">The URL helper.</param>
/// <param name="actionName">The name of the action method.</param>
/// <param name="controllerName">The name of the controller.</param>
/// <param name="routeValues">The route values.</param>
/// <returns>The absolute URL.</returns>
public static string AbsoluteAction(this UrlHelper url,
string actionName, string controllerName, object routeValues = null)
{
string scheme = url.RequestContext.HttpContext.Request.Url.Scheme;
return url.Action(actionName, controllerName, routeValues, scheme);
}
The method can then be called like this: @Url.AbsoluteAction("SomeAction", "SomeController")
精彩评论