2009-05-18 57 views
11

我有幾個頁面列出了搜索結果,對於我想要顯示的每個結果我想創建一個自定義的View Helper以避免重複顯示代碼。如何從自定義助手使用ASP.NET MVC Html Helpers?

如何從我的自定義視圖助手訪問方便的現有視圖助手?即在我的自定義視圖幫助器中,我想使用Url.Action(),Html.ActionLink等。我如何從我的自定義視圖幫助器中訪問它們?

using System; 
namespace MvcApp.Helpers 
{ 
    public class SearchResultHelper 
    { 
     public static string Show(Result result) 
     { 
      string str = ""; 

      // producing HTML for search result here 

      // instead of writing 
      str += String.Format("<a href=\"/showresult/{0}\">{1}</a>", result.id, result.title); 
      // I would like to use Url.Action, Html.ActionLink, etc. How? 

      return str; 
     } 
    } 
} 

using System.Web.Mvc可以訪問HtmlHelpers,但像ActionLink的便捷方法不似乎存在。

回答

8

這個例子可以幫助你。這個幫助器根據用戶是否登錄來呈現不同的鏈接文本。它演示瞭如何使用ActionLink的我的自定義幫助裏面:

public static string FooterEditLink(this HtmlHelper helper, 
     System.Security.Principal.IIdentity user, string loginText, string logoutText) 
    { 
     if (user.IsAuthenticated) 
      return System.Web.Mvc.Html.LinkExtensions.ActionLink(helper, logoutText, "Logout", "Account", 
       new { returnurl = helper.ViewContext.HttpContext.Request.Url.AbsolutePath }, null); 
     else 
      return System.Web.Mvc.Html.LinkExtensions.ActionLink(helper, loginText, "Login", "Account", 
       new { returnurl = helper.ViewContext.HttpContext.Request.Url.AbsolutePath }, null); 
    } 

編輯:
所有你需要做的訪問Url.Action()方法是用什麼來代替this HtmlHelper helper PARAM像this UrlHelper urlHelp,然後就請致電urlHelp.Action(...

希望這會有所幫助。

-1

在我看來,你不應該試圖在代碼中使用ActionLink。 MVC的整個概念是將邏輯與顯示分開,所以你應該試着堅持。

我建議你將結果對象傳遞給視圖(也許通過ViewData),然後在視圖內部解析結果。例如

<%= Html.ActionLink(result.title,"/showresult/" + result.id, "myController") %> 
+1

我明白你的觀點並表示同意。但是,這意味着我需要在幾個地方複製解析/顯示代碼/邏輯,這是我試圖避免的。 – stpe 2009-05-18 08:24:13

1

一個簡單的gravatar HTML helpler,你必須是靜態也。

public static string GetGravatarURL(this HtmlHelper helper, string email, string size, string defaultImagePath) 
    { 

     return GetGravatarURL(email, size) + string.Format("&default={0}", defaultImagePath); 

    } 
0

你可以擴展默認的HtmlHelper和UrlHelper只是一個擴展方法(讓你有xxxHelper在你的方法第一個參數)。

或者您可以使用所需的方法創建基本視圖,並使用該視圖的Html或URL變量。

相關問題