2009-09-18 18 views
162

HTMLヘルパーでURLを生成する

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

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

ただし、カスタムHTMLヘルパーから行う方法はわかりません。私は

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

ヘルパー変数はアクションと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のインスタンスを自分で扱いたいとは思わない。より簡単な方法が必要です。

+3

これは簡単な例ですが、ここに示した例では、HtmlHelperではなくUrlHelperを拡張しています。あなたの本当のコードは両方とも必要かもしれません。 –

+0

申し訳ありませんが、私はもっと明確にすべきでした。私は拡張メソッドでHTMLレンダリングをいくつかやりたかったので、URLの生成が必要でした。 –

答えて

206

あなたは、この内部のHTMLヘルパー拡張メソッドのようなURLヘルパーを作成することができます:あなたはしないでください。この例では

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

:あなたはまた、UrlHelperパブリックと静的クラスを使用してリンクを取得することができます

var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext); 
var url = urlHelper.Action("Home", "Index") 
+0

ああ、ありがとう。私はちょうど同じ:-)を投稿しました –

+2

コンストラクタもRouteCollectionを初期化すると良いでしょう。 '新しいUrlHelper(htmlHelper.ViewContext.RequestContext、htmlHelper.RouteCollection)' – kpull1

21

少し有利かもしれない新しいUrlHelperクラスを作成する必要があります。ここで

+0

RouteCollectionを設定するので、私はこの答えが好きです。 – kpull1

9

HtmlHelperインスタンスのUrlHelperを取得するための私の小さなextenstion方法である:

(私はこれが唯一の参考のためにANS掲示しています)

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

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]; 
     } 
    } 

は、としてそれを使用します

+0

新しいオブジェクトを作成するのではなく、既存のオブジェクトを再利用するため、優れたアプローチです。 – Mike

関連する問題