Search code examples
asp.net-mvctwitter-bootstraphtml-helper

MVC Html helper or partial view to reusable buttons


I have a button type that designed with bootstrap classes and I want to do this reusable.

My Edit Button

        <a href="@Url.Action("Edit", new {id = item.Id})" class="btn btn-warning btn-sm">
            <i class="glyphicon glyphicon-pencil"></i>
        </a>

My Delete Button

        <a href="@Url.Action("Delete", new {id = item.Id})" class="btn btn-danger btn-sm">
           <i class="glyphicon glyphicon-trash"></i>
       </a>

How can I do this format as reusable. With partials or with HtmlHelpers? Is there any sample?


Solution

  • As @ Stephen suggested you can use both,You can create a HTML Helpers by using the below code

    namespace System.Web.Mvc
    {
    
    public static class CustomHtmlHelpers
    {
    
        public static MvcHtmlString BootStarpDeleteHelper(this HtmlHelper htmlHelper, string action)
        {
            StringBuilder sb = new StringBuilder();  
            sb.Append("<a href=" + action + " class='btn btn-danger btn-sm'>");
            sb.Append("<i class='glyphicon glyphicon-trash'></i>");
            sb.Append("</a>");
            return MvcHtmlString.Create(sb.ToString());  
        }
    
    }
    

    }

    in the main view you can call the html helper like this

    @Html.BootStarpDeleteHelper("#");
    

    Else you can also create a partial view in the Shared folder and create a new partial view with name _BootStarpDelete

    The view look like this

    @{
      Layout = null;
    }
    <a href="@Url.Action("Delete", new {id = item.Id})" class="btn btn-danger btn-sm">
       <i class="glyphicon glyphicon-trash"></i>
    </a>
    

    In the main view you can render like this

    @Html.RenderPartial("_BootStarpDelete")
    

    Hope the above explanation will help you.If you want a single html helper for both edit and delete you need to pass classes as parameters.If the same if you want to do the partial view way then you have to pass a model with appropriate value such as action and classes