I ask a similar question here I think this is a really easy one (of course not for me). I have a extension method for Html helper and I need to get current view's url with HtmlHelper. Does anyone have any idea about it?
问题:
回答1:
Based on your comment and the original thread you linked to I think you want to use a Url helper to get the URL for the form action, but I could have misunderstood what you wanted:
In a View:
@Url.Action(null) returns the current controller/action
@Url.Action("Action") returns a custom action with current controller
@Url.Action("Action","Controller") returns a custom controller and action
In a HTML Helper:
public static MvcHtmlString MySpecialHelper(this HtmlHelper htmlHelper)
{
UrlHelper urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext,htmlHelper.RouteCollection);
string url = urlHelper.Action("Controller","Action");
//To get the action based on the current Action/Controller use:
url = urlHelper.Action(htmlHelper.ViewData["action"] as string);
//or
url = urlHelper.Action(null);
return new MvcHtmlString(url);
}
回答2:
if you want to get information about the route information , like the controller or action method that are called
you can access the RouteData
dictionary from the ViewContext
Object
will be like this
@ViewContext.RouteData.Values["Controller"]
with the RouteData
Dictionary you can get all the info needed about the controller , action and extra parameters' name , depending on what you want
回答3:
If you just want the requested url then you can just get it via the Request.Url
object. This returns a Uri, but if you want the raw url then Request.RawUrl
.
回答4:
You could use the Request.RawUrl property or Request.Url.ToString() or Request.Url.AbsoluteUri.
回答5:
You can use a Html Helper passing the object page as reference, like this:
@helper GoHome(WebViewPage page)
{
<a href="@page.Url.Action("Index", "Home")"></a>
}
An in the View just use:
@Links.GoHome(this)