Design Pattern - Creational - Builder

Scenario:

Create a custom CheckBox.

Solution:

Creational Pattern to separate the construction from representation, so same process to construct can give us different representation. 

Example: Create a custom checkbox, with additional attributes and enable/disable based on permissions for the user
  1. Take the label of checkbox, attributes and claim (permission) as input and then build the checkbox using builder pattern based on conditions:

  2.  1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    public static MvcHtmlString CheckBox(this HtmlHelper helper, string label, string claim, string httpMethod,
                object htmlAttributes)
    {
                var builder = new TagBuilder("input");
    
                builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
                builder.MergeAttribute("type", HtmlHelper.GetInputTypeString(InputType.CheckBox));
                if (IsAuthorized(claim, httpMethod) &&
                    !htmlAttributes.ToString().Contains("disabled"))
                {
                    builder.Attributes.Add("disabled", "disabled");
                }
    
                builder.InnerHtml = label;
                return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal));
    }

  3. Below is cshtml caller to render the checkbox using the above helper class

  4. 1
    2
    3
    4
    5
    <tr>
        <td class="">
            @Html.CheckBox("Delete User", "DeleteUser", "POST", new { name = "selectedDeleteUser", value = "1" })
        </td>
    </tr>

No comments:

Post a Comment

Move Github Sub Repository back to main repo

 -- delete .gitmodules git rm --cached MyProject/Core git commit -m 'Remove myproject_core submodule' rm -rf MyProject/Core git remo...