Asp.net mvc3中的自定义助手

时间:2011-09-10 12:24:38

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

我有一个ASP.NET MVC3应用程序。我想要一个自定义工具栏,我希望在每个表单中显示。这个自定义工具栏可以有一个或多个动作链接。所以,我需要开发一个我可以使用的自定义Html帮助器,如下所示;

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

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

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

  }

你能告诉我如何实现这个目标吗?如果你能指出适当的资源,那真的很棒..

非常感谢

此致..

1 个答案:

答案 0 :(得分:2)

这样的东西(我不知道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());
    }
}
相关问题