Custom HTML Helpers in ASP.NET MVC 2

青春壹個敷衍的年華 提交于 2019-12-11 06:49:30

问题


I want to create a pagination helper. The only parameters that it needs are currentpage, pagecount and routename. However, I do not know if it is possible to use the return value of another html helper inside the definition of my html helper. I am referring specifically to Html.RouteLink. How can I go about doing something like this in the class definition

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;

          }
     }
}

Thank you.


回答1:


Generally, yes you can use the results of other Html Helper functions within your custom functions. The exception would be any that write directly to the response stream rather than returning a string value.

I've done this sort of thing several times myself, and it works just fine...here's a sample I just totally made up right now based on something I did that I don't have the code for handy right now:

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();
}


来源:https://stackoverflow.com/questions/3032806/custom-html-helpers-in-asp-net-mvc-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!