我想修改像这样的助手:
<%= 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/