1

I want to write an extension method that will allow me to disable a control based on a security setting. The code below works and accomplishes what I want. However - because it creates an object that represents all html attributes - I cannot specifiy additional attributes other than the disabled attribute that this code generates.

public static class SecurityHtmlHelper
{
    public static object EnableForPermission(this HtmlHelper html, Permission permission)
    {
        if (Security.HasPermission(permission))
            return new object();
        else
            return new { disabled = "disabled" };
    }
}

Example of how the above is used:

  @Html.ActionLink("permission test", "/", null, @Html.EnableForPermission(Permission.PM_PROCEDURE_ALT_SCEN_READ))

Desired usage example (does not build):

  @Html.ActionLink("permission test", "/", null, new { @style ="xyz", @Html.EnableForPermission(Permission.PM_PROCEDURE_ALT_SCEN_READ)})

No I dont want to use javascript and yes I realize disabling a link does not prevent the user from navigating to a page there are other controls in place for that.

Thx.

For reference on disabled attribute: Correct value for disabled attribute

Community
  • 1
  • 1

1 Answers1

1

A disabled attribute wont work on an <a> tag (and its invalid html), but from your comments, you want to use the helper to apply it to controls anyway.

I'm not sure what Security.HasPermission(permission) does, but if its calling a service, then it does not belong in a helper. In any case I suggest you pass a boolean value to the view indicating if the permission applies, using a view model or ViewBag property, for example in the controller

ViewBag.HasPermission = Security.HasPermission(Permission.PM_PROCEDURE_ALT_SCEN_READ);

The helper needs to merge the html attributes you pass to it with the disabled attribute if applicable

public static IDictionary<string, object> EnableForPermission(object htmlAttributes, bool hasPermission)
{
  IDictionary<string, object> attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
  if (!hasPermission)
  {
    attributes.Add("disabled", "disabled");
  }
  return attributes;
}

and then in the view

@Html.TextBoxFor(m => m.someProperty, EnableForPermission(new { @class = "someClass" }, ViewBag.HasPermission))