对于 View ,我必须生成一些复选框。
我有一组元素:
public class ItemSelection
{
public int Id { get; set; }
public String Name { get; set; }
public Boolean IsSelected { get; set; }
public Boolean IsActive { get; set; }
}
在 View 中,我正在对此进行迭代
@foreach(ItemSelection item in Model.Items){
Html.CheckBoxFor(m=>item.IsSelected)//HERE I WOULD LIKE TO HAVE DISABLED properties if I've a IsActive=falsel
Html.HiddenFor(m=>item.Id)
}
现在我看到我可以做一个“如果”,在其中我根据这个属性创建一个不同的 HtmlAttribute 数组,但是有没有办法只创建一个数组
new {disabled=item.IsActive?"ONE_SPECIAL_VALUE_HERE":"disabled"}
我尝试输入 false
或其他一些东西,但没有任何效果。
最佳答案
你无法避免if
:
问题在于 disabled
属性的特殊性质,因为没有“特殊”值可以使您的示例工作,because :
"disabled" is only possible value for this attribute. If the input should be enabled, simply omit the attribute entirely.
因此您需要省略该属性以启用该控件,但所有 HTML 帮助程序将序列化作为 html 属性传入的匿名对象的所有属性。并且无法有条件地向匿名类型添加属性。
然而,如果您有多个用于启用/禁用情况的公共(public)属性,并且您不想创建两个匿名类型,您可以将这些属性放入一个字典中,并带有可选的 disabled
属性和使用字典作为 htmlAttributes:
var checkboxHtmlAttributes = new Dictionary<string, object>
{{"attibute1", "value1"},
{"attribute2", "value2"}};
if (!item.IsActive)
{
checkboxHtmlAttributes.Add("disabled", "disabled");
}
@Html.CheckBoxFor(m=>item.IsSelected, checkboxHtmlAttributes)
关于html - 如何使用 html 帮助程序进行条件检查、禁用等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10394311/