2009-05-18 69 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变量。

相关问题