ASP.NET MVC 2中的自定义HTML帮助程序

时间:2010-06-13 15:42:04

标签: asp.net-mvc-2 html-helper

我想创建一个分页助手。它需要的唯一参数是currentpage,pagecount和routename。 但是,我不知道是否可以在我的html帮助器定义中使用另一个html帮助器的返回值。我指的是Html.RouteLink。我怎样才能在类定义

中做这样的事情
using System;
using System.Web.Mvc;

namespace MvcApplication1.Helpers
{
     public static class LabelExtensions
     {
          public static string Label(this HtmlHelper helper, string routeName, int currentpage, int totalPages)
          {
               string html = "";
               //Stuff I add to html
               //I'd like to generate a similar result as the helper bellow. 
               //This code does not work, it's just an example of what I'm trying to accomplish
               html .= Html.RouteLink( pageNo, routeName, new { page = pageNo - 1 } );
               //Other stuff I do the html
               return html;

          }
     }
}

谢谢。

1 个答案:

答案 0 :(得分:3)

通常,是的,您可以在自定义函数中使用其他Html Helper函数的结果。例外是任何直接写入响应流而不是返回字符串值的例外。

我自己已经做了好几次这样的事情,而且效果很好......这是我刚刚完成的一个示例,基于我所做的事情,我现在没有方便的代码:

public static string RssFeed(this HtmlHelper helper, string url)
{
    StringBuilder sb = new StringBuilder();
    sb.Append(GetRSSMarkup(url));  // This generates the markup for the feed data
    sb.Append(helper.ActionLink("Go Home","Index","Home"));
    return sb.ToString();
}