ASP.NET MVC中禁用复选框的属性 [英] Checkbox disabled attribute in ASP.NET MVC

查看:79
本文介绍了ASP.NET MVC中禁用复选框的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的ViewModel具有selected和selectable的属性.两者都是布尔值.我希望我的视图有一个复选框,当selectable为true时启用,而selectable为false则禁用.完成此操作的合适剃刀语法是什么?

My ViewModel has a property of selected and selectable. Both are boolean. I would like my view to have a checkbox that is enabled when selectable is true and disabled when selectable is false. What is the proper razor syntax to accomplish this ?

我在表格的项目列表上尝试了下面的代码.不论可选值如何,每行都会返回一个禁用的复选框.

I tried the code below on a list of items in a table. Every row comes back with a disabled checkbox regardless of selectable value.

 @Html.CheckBoxFor(modelItem => item.Selected, new { @disabled = !item.Selectable })

推荐答案

使用if条件内部方法来实现此目标并不容易,因为以下所有标记都会导致禁用chechbox.

It is not easy to achieve this with an if condition inside the helper method because all the below markups will render a disabled chechbox.

<input type="checkbox" disabled>
<input type="checkbox" disabled="disabled">
<input type="checkbox" disabled="false">
<input type="checkbox" disabled="no">
<input type="checkbox" disabled="enabled">

这应该在剃须刀中起作用.简单的If条件并呈现所需的内容.

This should work in the razor. Simple If condition and rendering what you want.

@if(item.Selected)
{ 
  @Html.CheckBoxFor(modelItem => item.Selected)
}
else
{
    @Html.CheckBoxFor(modelItem => item.Selected, new { @disabled = "disabled"})
}

您可以考虑编写一个自定义html帮助器,以为此呈现适当的标记.

You may consider writing a custom html helper which renders the proper markup for this.

这篇关于ASP.NET MVC中禁用复选框的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆