【问题标题】:Custom Helper in Asp.net mvc3Asp.net mvc3 中的自定义助手
【发布时间】:2011-11-14 08:37:13
【问题描述】:

我有一个 ASP.NET MVC3 应用程序。我想要一个自定义工具栏,我想以每种形式显示。这个自定义工具栏可以有一个或多个操作链接。所以,我需要开发一个自定义 Html 助手,我可以使用如下所示;

@Html.CustomToolBar(items => {
          items.Add("Action","Controller","Name","Text");
          items.Add("Action1","Controller1","Name1","Text1");})

此自定义扩展将生成链接 html,并将其显示在我的表单上。我有一个ToolBarAction 课程,我想从@Html.CustomToolBar 获得List<ToolBarAction>

  public class ToolbarAction
  {
    public string Name { get; set; }
    public string Action { get; set; }
    public string Controller { get; set; }
    public string Text { get; set; }

  }

您能告诉我如何实现这一目标吗?如果您能给我指出适当的资源,那就太好了..

非常感谢

问候..

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-3 lambda


    【解决方案1】:

    类似这样的东西(我不知道 Name 属性是干什么用的,所以我将它添加为类):

    public static class HelperExtensions
    {
        public static MvcHtmlString Menu(this HtmlHelper html, Action<IList<ToolbarAction>> addActions)
        {
            var menuActions = new List<ToolbarAction>();
            addActions(menuActions);
    
            var htmlOutput = new StringBuilder();
    
            htmlOutput.AppendLine("<div id='menu'>");
    
            foreach (var action in menuActions)
                htmlOutput.AppendLine(html.ActionLink(action.Text, action.Action, action.Controller, new { @class = action.Name }).ToString());
    
            htmlOutput.AppendLine("</div>");
    
            return new MvcHtmlString(htmlOutput.ToString());
        }
    }
    

    【讨论】:

    • 它与问题中的代码相同,只是我将方法命名为Menu 而不是CustomToolBar
    猜你喜欢
    • 2012-09-04
    • 2011-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    相关资源
    最近更新 更多