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

查看:34
本文介绍了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 条件 inside 辅助方法来实现这一点并不容易,因为以下所有标记将呈现禁用的复选框.

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天全站免登陆