1
votes

I want to modify helpers such as this one:

<%= Html.CheckBoxFor(m => m.Current, new { @class = "economicTextBox", propertyName = "Current", onchange = "UseCurrent();UpdateField(this);" })%>

to also take as a parameter another string that signifies a permission in the app, and then INSIDE the method I would determine whether or not to return the actual HTML or nothing, depending on their permission.

How would I do this?

UPDATE 2: Checkbox not rendering as readonly

When I debug and check the value of htmlHelper.CheckBoxFor(expression, mergedHtmlAttributes)._value, I get this

<input checked="checked" class="economicTextBox" id="Current" name="Current" onchange="UseCurrent();UpdateField(this);" propertyName="Current" readonly="true" type="checkbox" value="true" /><input name="Current" type="hidden" value="false" />

but the checkbox is still rendering allowing me to change it and achieve full functionality. Why?

2

2 Answers

3
votes

You could write a custom helper:

public static MvcHtmlString MyCheckBoxFor<TModel>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, bool>> expression, 
    string permission, 
    object htmlAttributes
)
{
    if (permission == "foo bar")
    {
        // the user has the foo bar permission => render the checkbox
        return htmlHelper.CheckBoxFor(expression, htmlAttributes);
    }
    // the user has no permission => render empty string
    return MvcHtmlString.Empty;
}

and then:

<%= Html.CheckBoxFor(
    m => m.Current, 
    "some permission string",
    new {  
        @class = "economicTextBox", 
        propertyName = "Current", 
        onchange = "UseCurrent();UpdateField(this);" 
    }) 
%>

UPDATE:

Here's how you could modify the HTML helper so that it renders a readonly checkbox instead of an empty string if the user has no permissions:

public static MvcHtmlString MyCheckBoxFor<TModel>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, bool>> expression,
    string permission,
    object htmlAttributes
)
{
    if (permission == "foo bar")
    {
        // the user has the foo bar permission => render the checkbox
        return htmlHelper.CheckBoxFor(expression, htmlAttributes);
    }
    // the user has no permission => render a readonly checkbox
    var mergedHtmlAttributes = new RouteValueDictionary(htmlAttributes);
    mergedHtmlAttributes["readonly"] = "readonly";
    return htmlHelper.CheckBoxFor(expression, mergedHtmlAttributes);
}
2
votes

In order to do what you want, you need to create you own HTML Helper. The HTML Helper methods are just extension methods. As such you can easily create your own that does the proper permission checking and then if it passes, call the default Html.CheckBoxFor with the rest of the parameters.

This previous question has a decent example of creating custom helpers.