Html.Checkbox does not preserve its state in ASP.net MVC

人走茶凉 提交于 2019-12-13 07:32:52

问题


I have this annoying issue with the checkbox created using the Html.Checkbox extension method. Apparently the state of the checkbox is not saved in case of a postback (due to a form validation error). Delving into the MVC code itself (System.Web.Mvc.Html.InputExtensions) I found out that the 'checked' property is determined by calling htmlHelper.EvalBoolean(name).

This method looks for the key (specified in the name argument) of the ViewData itself. The problem is that the value of the checkbox is actually located in the ModelState. Calling htmlHelper.GetModelStateValue(name, typeof(bool)) would return the expected result.

Is this a flaw in the checkbox implementation ?


回答1:


I posted another workaraound here:

How to maintain state of Html.CheckBox() in ASP.NET MVC




回答2:


This issue was posted on codeplex and will be fixed/supported in the MVC RTM. In the meantime, this is a nice workaround.




回答3:


Remember that the ideaology behind MVC is to move the web back to the way it was a few years ago. You are not supposed to have postbacks on a page without using something like AJAX. As such, most controls that you are used to maintaining their own state will no longer do.

Have you thought of using AJAX to try solve this problem? That way you can have your postbakc and maintain the state of the control?



来源:https://stackoverflow.com/questions/526310/html-checkbox-does-not-preserve-its-state-in-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!