[英]C# MVC - How to display an uneditable checkbox with an id so I can grab it with Jquery
I've come across an issue with a field bound to a bool. 我遇到了一个与布尔绑定的问题。
I want to show a checkbox representing a bool field in my model. 我想显示一个代表模型中布尔字段的复选框。 I don't want the user to be able to edit it. 我不希望用户能够对其进行编辑。 But I need to be able to edit it's checked state using jquery - and for this it needs to have an id. 但是我需要能够使用jquery编辑它的检查状态-为此,它需要有一个id。
I can't seem to do it. 我似乎做不到。 Here's what I have tried: 这是我尝试过的:
@Html.DisplayFor(m => m.Deleted, null)
This shows the correct checked state but there's no id on the checkbox. 这显示了正确的检查状态,但是复选框上没有ID。
I noticed that using EditorFor you can apply HTML Attributes in the below fashion, but it doesn't work in DisplayFor - they are ignored. 我注意到使用EditorFor可以按以下方式应用HTML属性,但在DisplayFor中不起作用-它们将被忽略。
@Html.DisplayFor(m => m.Deleted, new { htmlAttributes = new { @id = "cbCourtDeleted" } })
So I then thought I could use and EditorFor and apply readonly
and disabled
attributes (i've done this with textboxfor before and it works well: 因此,我以为我可以使用andEditorFor并应用readonly
和disabled
属性(我之前已经使用textboxfor做到了,而且效果很好:
@Html.EditorFor(m => m.Deleted, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly", @disabled = "disabled", @id = "cbCourtDeleted" } })
but when used in Editor for (for checkboxes at least) the checked state isn't displayed - it appears unchecked, but it does have the required id. 但是当在编辑器中用于(至少用于复选框)时,不显示已选中状态-看起来未选中,但确实具有必需的ID。
Question: How can I display a bool field from my model that has an id so I can get access to it via jquery/javascript? 问题:如何从模型中显示具有ID的bool字段,以便可以通过jquery / javascript访问它?
@Html.CheckBoxFor(m => m.Deleted, new { @id = "chkDeleted", @disabled = "true"})
The HTML input element will have id
and name
attributes set to the property name of the model class, setting the id with an attribute is probably not needed, HTML input元素将id
和name
属性设置为模型类的属性名称,可能不需要使用属性设置id,
@Html.CheckBoxFor(m => m.Deleted)
When the checkbox will not allow editing, and if the disabled
attribute is used to prevent editing, it might help to add another property to the model for returning the value back to the server, since the browser does not return values of disabled inputs. 如果该复选框不允许编辑,并且如果disabled
属性用于阻止编辑,则由于浏览器不会返回禁用输入的值,因此可能有助于向模型添加另一个属性以将值返回给服务器。 This new property can be a hidden field and can be set with JQuery. 这个新属性可以是一个隐藏字段,并且可以使用JQuery进行设置。
@Html.CheckBoxFor(m => m.Deleted, new { disabled = "disabled" })
@Html.HiddenFor(m => m.DeletedAndBackToServer)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.