ここで同様の質問をしますが、これは本当に簡単なものだと思います (もちろん、私にとっては違います)。Html ヘルパーの拡張メソッドがあり、HtmlHelper で現在のビューの URL を取得する必要があります。誰かそれについて何か考えがありますか?
6 に答える
あなたのコメントとあなたがリンクした元のスレッドに基づいて、フォームアクションの URL を取得するために Url ヘルパーを使用したいと思いますが、あなたが望んでいたものを誤解していた可能性があります。
ビューで:
@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
HTML ヘルパーでは:
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);
}
呼び出されるコントローラやアクションメソッドなど、ルート情報に関する情報を取得する場合
オブジェクトRouteData
から辞書にアクセスできますViewContext
このようになります
@ViewContext.RouteData.Values["Controller"]
辞書を使用すると、RouteData
必要なものに応じて、コントローラー、アクション、および追加のパラメーターの名前について必要なすべての情報を取得できます。
要求された URL だけが必要な場合は、Request.Url
オブジェクトを介して取得できます。これは Uri を返しますが、生の URL が必要な場合はRequest.RawUrl
.
ネクロマンシング
public static MvcHtmlString MyHelper(this HtmlHelper htmlHelper)
{
var url = htmlHelper.ViewContext.HttpContext.Request.Url;
//more code
}
OPは「Htmlヘルパーの拡張方法」について尋ねました-そうです、これです。
Request.RawUrl プロパティ、Request.Url.ToString()、または Request.Url.AbsoluteUri を使用できます。
次のように、オブジェクト ページを参照として渡す Html ヘルパーを使用できます。
@helper GoHome(WebViewPage page)
{
<a href="@page.Url.Action("Index", "Home")"></a>
}
ビューで使用するだけです:
@Links.GoHome(this)