ASP.NET:如何使复选框即使在提交后也始终处于未选中状态
刚刚开始学习如何开发 ASP.NET 应用程序,我很困惑如何使复选框始终处于未选中状态,即使在提交用户勾选复选框的表单后也是如此。该复选框用于确认用户同意条款和条件...当表单提交返回一些错误时,我想在屏幕上显示错误消息并保持复选框处于未选中状态,无论是否选中。
在我看来,我有以下内容:
<%: Html.CheckBoxFor(m => m.UserAgreement) %>
我已经在我的控制器中尝试了以下两种方法,但都不起作用:
ViewData["UserAgreement"] = false;
return View(new MyModel { UserAgreement = false});
任何人都可以帮助如何实现我所需要的?谢谢。
Just started learning how to develop a ASP.NET application, i am puzzled on how to make a checkbox is always unchecked even after form submit where a user tick the checkbox. The checkbox is for acknowledgment that user agrees to the terms and conditions ... and when form submit return some errors I want to display the error message on the screen and keep the checkbox unchecked regardless it was ticked or not.
In my view I have the following:
<%: Html.CheckBoxFor(m => m.UserAgreement) %>
And I have tried both the following in my controller and none of them works:
ViewData["UserAgreement"] = false;
return View(new MyModel { UserAgreement = false});
Anyone can help on how to achieve what I need? Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这也困扰了我很长一段时间,即使明确地将模型中的值设置为 false 也没有真正解决这个问题。我发现它还在检查 ModelState 集合中的值。
这可能不是最干净的解决方案,但这最终对我有用:
This bothered me for a long time as well, even explicity setting the values in my model to false did not really solve this problem. What I found was that it was also checking the value in the ModelState collection.
This is probably not the cleanest solution but this is ultimately what worked for me:
ASP.NET MVC CheckBox 不会保留其状态,除非您明确指示它这样做。
您上面发布的代码指示返回视图时应检查“UserAgreement”(值为 TRUE),而不是应取消选中它。
除非您在将视图返回给用户之前专门将 UserAgreement 的值设置为“true”,否则该复选框将被取消选中。同样,如果您的操作正在接收 UserAgreement 属性设置为“true”的模型,并且在将其返回到视图之前未将其设置回“false”,则该复选框将保持选中状态。
The ASP.NET MVC CheckBox does not retain its state unless you specifically tell it to do so.
The code you posted above indicates that 'UserAgreement' should be checked (value is TRUE) when the view is returned, not that it should be unchecked.
Unless you specifically set the value of UserAgreement to 'true' before returning the view to the user, the checkbox will be unchecked. Similarly, if your action is receiving a model with the UserAgreement property set to 'true' and you do not set it back to 'false' before returning it to the view, the checkbox will remain checked.
您的值将保存在 ModelState 属性中。为了在发布后重置该值。您必须清除 ModelState 属性中的值
Your value is being saved in the ModelState property. In order to reset the value after a post. You have to cleaer the value in the ModelState property
在返回视图之前尝试
ModelState.Remove("UserAgreement");
。Try
ModelState.Remove("UserAgreement");
before you return the view.