MVC3 WebGrid Page/Sort Issue with a CheckBox elsewhere on the page

雨燕双飞 提交于 2019-12-07 15:37:58

问题


I have a checkbox on my page, created as such:

@Html.CheckBoxFor(x => x.MyBoolValue)   

Beneath that I have a WebGrid with sorting and paging, but on doing this I get a System.InvalidOperationException:

The parameter conversion from type 'System.String' to type 'System.Boolean' failed. See the inner exception for more information.

The inner exception is:

{"true,false is not a valid value for Boolean."}

I know this is due to the binding of the CheckBox and the underlying Hidden value. On a page GET I deal with this using Contains("true") on the query string value, but how can I do this when the WebGrid is refreshed?


回答1:


MVC creates two inputs on @Html.CheckBoxFor(x => x.MyBoolValue). One Checkbox and one hidden field with the value false.

He (MVC ;)) does this ensure that, even if you dont check the checkbox, the variable exists. So if you check the box the variable value is true,false and false if not.

do this:

<input type="CheckBox" name="MyBoolValue" value="@Model.MyBoolValue"/>

or create a custom model binder that handles that.

ASP.NET MVC Custom Model Binding




回答2:


If you want to maintain all standard validators or binders functionality and hidden field bother you someway. You can use this:

<input type="CheckBox"@(Model.BoolProperty ? " checked=\"checked\"" : string.Empty) name="BoolProperty" value="true"/>



回答3:


I have found that removing the value from the ModelState resolves this, and doesn't seem to cause any side effects - perhaps someone could point out if I've missed anything?

In my controller I just add

ModelState.Remove("MyBoolValue");

Which means that

@Html.CheckBoxFor(x => x.MyBoolValue)   

will fallback to using the Model value unless I'm mistaken?




回答4:


The problem is the name of your action parameter:

public ActionResult Product(ProductModel model); 

For example the following will fix your issue:

public ActionResult Product(ProductModel request); 


来源:https://stackoverflow.com/questions/8164546/mvc3-webgrid-page-sort-issue-with-a-checkbox-elsewhere-on-the-page

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