169

通常、ASP.NETビューでは、次の関数を使用してURL(ではなく<a>)を取得できます。

Url.Action("Action", "Controller");

ただし、カスタムHTMLヘルパーからそれを行う方法を見つけることができません。私は持っています

public class MyCustomHelper
{
   public static string ExtensionMethod(this HtmlHelper helper)
   {
   }
}

ヘルパー変数にはActionメソッドとGenerateLinkメソッドがありますが、これらはを生成し<a>ます。ASP.NET MVCソースコードを掘り下げましたが、簡単な方法を見つけることができませんでした。

問題は、上記のUrlがビュークラスのメンバーであり、そのインスタンス化のために、いくつかのコンテキストとルートマップが必要なことです(これは扱いたくないので、とにかくそうする必要はありません)。あるいは、HtmlHelperクラスのインスタンスには、Urlインスタンスのコンテキスト情報のサブセットの夕食であると私が想定するコンテキストもあります(ただし、これも扱いたくありません)。

要約すると、それは可能だと思いますが、私が見ることができるすべての方法は、多かれ少なかれ内部ASP.NETのものを使った操作を伴うため、より良い方法があるかどうか疑問に思います。

編集:たとえば、私が見る1つの可能性は次のとおりです。

public class MyCustomHelper
{
    public static string ExtensionMethod(this HtmlHelper helper)
    {
        UrlHelper urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
        urlHelper.Action("Action", "Controller");
    }
}

しかし、それは正しくないようです。UrlHelperのインスタンスを自分で処理したくありません。もっと簡単な方法があるはずです。

4

3 に答える 3

220

htmlヘルパー拡張メソッド内で次のようなURLヘルパーを作成できます。

var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
var url = urlHelper.Action("Home", "Index")
于 2009-09-18T10:27:57.850 に答える
22

UrlHelperpublicクラスとstaticクラスを使用してリンクを取得することもできます。

UrlHelper.GenerateUrl(null, actionName, controllerName, null, null, null, routeValues, htmlHelper.RouteCollection, htmlHelper.ViewContext.RequestContext, true)

この例では、少し利点となる可能性のある新しいUrlHelperクラスを作成する必要はありません。

于 2013-01-24T10:20:47.063 に答える
10

インスタンスを取得UrlHelperするための私の小さな拡張メソッドは次のとおりです。HtmlHelper

  public static partial class UrlHelperExtensions
    {
        /// <summary>
        /// Gets UrlHelper for the HtmlHelper.
        /// </summary>
        /// <param name="htmlHelper">The HTML helper.</param>
        /// <returns></returns>
        public static UrlHelper UrlHelper(this HtmlHelper htmlHelper)
        {
            if (htmlHelper.ViewContext.Controller is Controller)
                return ((Controller)htmlHelper.ViewContext.Controller).Url;

            const string itemKey = "HtmlHelper_UrlHelper";

            if (htmlHelper.ViewContext.HttpContext.Items[itemKey] == null)
                htmlHelper.ViewContext.HttpContext.Items[itemKey] = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);

            return (UrlHelper)htmlHelper.ViewContext.HttpContext.Items[itemKey];
        }
    }

次のように使用します。

public static MvcHtmlString RenderManagePrintLink(this HtmlHelper helper, )
{    
    var url = htmlHelper.UrlHelper().RouteUrl('routeName');
    //...
}

(私はこの回答を参照用にのみ投稿しています)

于 2013-05-29T11:13:32.253 に答える