Custom Helper in Asp.net mvc3

2019-05-07 17:16发布

问题:

I have an ASP.NET MVC3 application. I would like to have a custom toolbar that I want to display in every form. This custom toolbar can have one or many action links.So, I need to develop a Custom Html helper that I can use like below;

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

This custom extension will produce the links html and I will display it on my form. I have a ToolBarAction class and I would like to get List<ToolBarAction> from @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; }

  }

Can you advise me how I can achieve this? If you could point me the appropriate resources, that would be great really..

Many thanks

Regards..

回答1:

Something like this (I didn't know what the Name property was for, so I added it as the class):

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