动态CheckBoxFor有一些禁用

时间:2012-04-12 22:47:35

标签: asp.net asp.net-mvc-3 checkbox

我正在尝试创建一个动态CheckBoxFor,其中某些项被禁用。

这会禁用所有内容:

@Html.CheckBoxFor(m=>m.Checked, new { @disabled = "disabled"})

我试图创造这样的东西但没有成功:

@Html.CheckBoxFor(m=>m.Checked, new{ @disabled = @(Model.Disable ? "disabled" : "")})

请注意,我的模型有一个名为Disabled的属性和另一个Checked。

1 个答案:

答案 0 :(得分:7)

它不起作用,因为disabled属性会禁用CheckBox,无论它的值是什么。

我不知道如何在一行中做到这一点,但这是一个解决方案:

@if(Model.Disabled)
{ 
    @Html.CheckBoxFor(m=>m.Checked, new { @disabled = "disabled"})
}
else
{
    @Html.CheckBoxFor(m=>m.Checked)
}

潜在的Html Helper扩展:

public static MvcHtmlString CheckBoxFor<TModel>(
        this HtmlHelper<TModel> helper,
        Expression<Func<TModel, bool>> expression,
        object htmlAttributes,
        bool isDisabled)
{
    var dic = htmlAttributes.GetType()
             .GetProperties()
             .ToDictionary(p => p.Name, p => p.GetValue(htmlAttributes, null));

    if (isDisabled)
        dic["disabled"] = "disabled";

    return helper.CheckBoxFor(expression, dic);
}