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
- Take the label of checkbox, attributes and claim (permission) as input and then build the checkbox using builder pattern based on conditions:
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));
} |
- Below is cshtml caller to render the checkbox using the above helper class
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