c# - 修改 ASP.NET MVC 2 中的 HTML Helpers

标签 c# .net asp.net-mvc-2 permissions html-helper

我想修改像这样的助手:

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

还将另一个表示应用程序权限的字符串作为参数,然后在方法内部我将根据他们的权限确定是否返回实际的 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 Helpers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4681592/

相关文章:

c# - 1000个用户可以同时阅读单个文本吗?

c# - Razor Page - 当存储在 html 数据属性中时,C# 代码中带有空格的字符串会被缩短

c# - 扩展方法和源代码的向前兼容性

asp.net-mvc-2 - 登录页面重定向

jquery - 在 ASP.NET MVC 中显示 Json 错误消息

javascript - 在更改时使用 javascript 函数时将样式添加到 html.dropdownlist

c# - 将平面列表转换为对象

c# - 将类型从字符串变量发送到泛型方法

c# - 为什么 Calli 比委托(delegate)调用更快?

.net - 在 C++ 程序和 .NET 程序之间进行远程调用的最简单方法