[英]Usage of checkboxfor & model in asp.net mvc c#
I have a model 我有一个模特
public int Id { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public bool IsChecked { get; set; }
I want to use checkboxfor in my view 我想在我的视图中使用checkboxfor
@Html.CheckBoxFor(model => model.IsChecked, new{@checked="checked"})
My checkbox is unchecked and view renders additional input 我的复选框未选中,并且视图呈现其他输入
<input name="IsChecked" type="hidden" value="false">
I don't understand how does it work? 我不知道它是如何工作的? And how do i pass checkbox bool value to my model? 以及如何将复选框布尔值传递给我的模型? Thanks. 谢谢。
If model.IsChecked
is true when the control is rendered the checkbox will start as checked. 如果在呈现控件时model.IsChecked
为true,则复选框将以选中状态启动。
So just write: 所以只要写:
@Html.CheckBoxFor(m => m.IsChecked)
The hidden field is generated always false by the helper method to make sure the propery name/value is submitted when the form posts even if the checkbox isnt cjecked by the user, because html forms only include checked checkboxes. 隐藏字段由helper方法生成始终为false,以确保表单发布时属性名称/值被提交,即使该复选框没有被用户选中,因为html表单仅包括选中的复选框。
If the checkbox IS checked its property will take presedence over the hidden field because it comes before it. 如果选中此复选框,则其属性将优先于隐藏字段,因为它位于该字段之前。
C#.NET MVC has some issues with CheckBoxFor() command. C#.NET MVC在CheckBoxFor()命令中存在一些问题。 CheckBoxFor() autogenerates a hidden field with the same name & if it is not isolated in a [Div] by itself, it will sporadically drop checks going to the server. CheckBoxFor()会自动生成一个具有相同名称的隐藏字段,并且如果未单独将其隔离在[Div]中,则会偶尔将支票丢到服务器上。 Even including a title or validation inside the [display-field] div can cause an issue with a CheckBoxFor(). 即使在[display-field] div中包含标题或验证,也可能导致CheckBoxFor()出现问题。 Workarounds are to isolate CheckBoxFor() or add [onchange] update & it seems to work more consistently. 解决方法是隔离CheckBoxFor()或添加[onchange]更新,并且看起来工作更一致。
<div class="display-field">
@Html.CheckBoxFor(m => Model.IsChecked,
new { onchange = "this.value = this.checked;"})
</div>
The server side should now catch true false into a bool model with the same name automatically. 现在,服务器端应自动将true false捕获到具有相同名称的bool模型中。
public bool IsChecked { get; set; }
currently using MVC 4.x on VS 2017 PRO 当前在VS 2017 PRO上使用MVC 4.x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.