在没有 HTML 帮助器的情况下手动将 MVC 模型绑定到复选框
我正在从包含三个字段的 ViewModel 对象数组构建一个屏幕:
public class StartViewModel {
public string Id{ get; set; }
public string Name { get; set; }
public bool Accept { get; set; }
}
然后我尝试将其绑定到我的视图,如下所示:
<input type="hidden" name="StartRequests[<%: i.ToString() %>].Name" value="<%: StartRequests.Name %>" />
<input type="hidden" name="StartRequests[<%: i.ToString() %>].Id" value="<%: StartRequests.Id%>" />
然后我想将 Accept 标志绑定到复选框。我知道该复选框缺少名称属性,因此我无法立即使用它,并且我知道 Html.CheckBoxFor 将生成第二个隐藏字段来存储该值。这是我的问题。
我没有使用javascript的能力。我需要配置此复选框以有效调整 ViewModel 中的值,但我不知道如何实现这一点。 Html.CheckBox 帮助器如何填充它生成的隐藏字段?我以为它是用 javascript 实现的。有人可以帮助我理解一种方法吗?我仍在研究模型绑定背后的想法。
I am building a screen from an array of ViewModel objects that contain three fields:
public class StartViewModel {
public string Id{ get; set; }
public string Name { get; set; }
public bool Accept { get; set; }
}
I am then trying to bind it to my view like so:
<input type="hidden" name="StartRequests[<%: i.ToString() %>].Name" value="<%: StartRequests.Name %>" />
<input type="hidden" name="StartRequests[<%: i.ToString() %>].Id" value="<%: StartRequests.Id%>" />
I then want to bind the Accept flag to a checkbox. I understand that the checkbox lacks a name attribute so I can't use it immediately and I understand that the Html.CheckBoxFor will generate a second hidden field that will store the value. So here is my issue.
I do not have the ability to use javascript. I need to configure this checkbox to effectively adjust the value in the ViewModel but I do not know how to make this happen. How do the Html.CheckBox helper populate the hidden field that it generates? I assumed it did so with javascript. Can someone help me understand a way to do this? I am still working through the ideas behind Model binding.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于以下型号:
解决方案:
更改 public bool Accept { get;放; } 到
public string Accept { get;放; }
提交时,如果选中复选框,则“Accept”值=“on”。您可以顺便检测检查值。
For following model:
The solution:
Change
public bool Accept { get; set; }
topublic string Accept { get; set; }
When submit, if checkbox is checked, The "Accept" value = "on". You can detect checked value by the way.