我认为他们可以,但我没有把我的钱放在我的嘴(这么说)设置只读属性实际上似乎没有做任何事情。
我宁愿不使用Disabled,因为我希望选中的复选框与表单的其余部分一起提交,我只是不希望客户端能够在某些情况下更改它们。
我认为他们可以,但我没有把我的钱放在我的嘴(这么说)设置只读属性实际上似乎没有做任何事情。
我宁愿不使用Disabled,因为我希望选中的复选框与表单的其余部分一起提交,我只是不希望客户端能够在某些情况下更改它们。
当前回答
很晚才开始,但我找到了MVC的答案 我禁用了复选框,并在复选框之前添加了一个HiddenFor,因此当它发布时,如果首先找到隐藏字段并使用该值。这是可行的。
<div class="form-group">
@Html.LabelFor(model => model.Carrier.Exists, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.HiddenFor(model => model.Carrier.Exists)
@Html.CheckBoxFor(model => model.Carrier.Exists, new { @disabled = "disabled" })
@Html.ValidationMessageFor(model => model.Carrier.Exists)
</div>
</div>
其他回答
如果你想要你所有的复选框都是“锁定”的,这样用户就不能改变“checked”状态,如果“readonly”属性是存在的,那么你可以使用jQuery:
$(':checkbox').click(function () {
if (typeof ($(this).attr('readonly')) != "undefined") {
return false;
}
});
这段代码很酷的一点是,它允许您在整个代码中更改“readonly”属性,而不必重新绑定每个复选框。
它也适用于单选按钮。
我只是不希望客户在某些情况下能够更改它们。
READONLY本身不起作用。你可能可以用CSS做一些奇怪的事情,但我们通常只是禁用它们。
警告:如果它们被发布回来,那么客户端可以更改它们,句号。你不能依靠只读来阻止用户修改某些东西。总是可以使用fiddler或只是改变html w/firebug或诸如此类的东西。
只读对<input type='checkbox'>无效
所以,如果你需要从表单中禁用的复选框中提交值,你可以使用jQuery:
$('form').submit(function(e) {
$('input[type="checkbox"]:disabled').each(function(e) {
$(this).removeAttr('disabled');
})
});
通过这种方式,在提交表单时从元素中删除禁用属性。
我会对ConroyP的回答进行评论,但这需要50个声望,而我没有。我确实有足够的声誉来发布另一个答案。对不起。
The problem with ConroyP's answer is that the checkbox is rendered unchangeable by not even including it on the page. Although Electrons_Ahoy does not stipulate as much, the best answer would be one in which the unchangeable checkbox would look similar, if not the same as, the changeable checkbox, as is the case when the "disabled" attribute is applied. A solution which addresses the two reasons Electrons_Ahoy gives for not wanting to use the "disabled" attribute would not necessarily be invalid because it utilized the "disabled" attribute.
假设有两个布尔变量$checked和$disabled:
if ($checked && $disabled)
echo '<input type="hidden" name="my_name" value="1" />';
echo '<input type="checkbox" name="my_name" value="1" ',
$checked ? 'checked="checked" ' : '',
$disabled ? 'disabled="disabled" ' : '', '/>';
如果$checked为true,则复选框显示为选中。如果$checked为false,则该复选框显示为未选中。当且仅当$disabled为false时,用户可以更改复选框的状态。当复选框未选中时,不管用户是否选中,“my_name”参数都不会发布。“my_name=1”参数在复选框被选中时被发布,无论用户是否选中。我相信这就是Electrons_Ahoy一直在寻找的。
如果其他人使用MVC和编辑器模板,这就是我如何控制显示只读属性(我使用自定义属性来获取If语句中的值)
@if (true)
{
@Html.HiddenFor(m => m)
@(ViewData.Model ? Html.Raw("Yes") : Html.Raw("No"))
}
else
{
@Html.CheckBoxFor(m => m)
}