我想修改这样的助手:

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


还将另一个表示应用程序中权限的字符串作为参数,然后在该方法的INSIDE内,根据其权限确定是否返回实际的HTML或不返回任何内容。

我该怎么做?

更新2:复选框不呈现为只读

当我调试并检查htmlHelper.CheckBoxFor(expression,mergedHtmlAttributes)._ value的值时,我得到了

<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" />


但该复选框仍在渲染,允许我对其进行更改并实现全部功能。为什么?

最佳答案

您可以编写一个自定义帮助器:

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;
}


然后:

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




更新:

修改HTML帮助器的方法如下:如果用户没有权限,它会呈现一个只读复选框,而不是一个空字符串:

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);
}

关于c# - 修改ASP.NET MVC 2中的HTML帮助器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4681592/

10-15 03:03