开发者

The string was not identified as a valid Boolean string

开发者 https://www.devze.com 2022-12-13 09:44 出处:网络
I have a page where I list checkboxes named TimeRange1, TimeRange2.... TimeRange7, and I generate them in a for loop like this:

I have a page where I list checkboxes named TimeRange1, TimeRange2.... TimeRange7, and I generate them in a for loop like this:

<% for (int currentDay = 1; currentDay <= 7; currentDay++)
......<%= Html.CheckBox("TimeRange" + currentDay.ToString(), false)%>

Works fine til I post the form, then I get a "The string was not identified as a valid Boolean string."

Apparently the problem is that I concatenate the name of the checkbox.

Is there some neat way of fixing this? I need to have them named 1-7. It's like a big schedule where you select w开发者_Go百科hich times should be available.


Try without helpers:

<% for (int currentDay = 1; currentDay <= 7; currentDay++) { %>
    <input type="checkbox" name="TimeRange<%= currentDay.ToString() %>" />
<% } %>

Html Helpers get their values from :

  1. ViewData.ModelState["controlName"].Value.RawValue.
  2. value parameter passed to HTML helper method.

They also generate a hidden input field in addition to the checkbox. So depending on the context sometimes you may end up with markup like this:

<input type="checkbox" name="TimeRange1" value="SomeValue, false" />

and when you post the form the data binder will be unable to convert the value to a boolean type.


An addition to this ol' question - might save someone a headache. I had accidentally labeled a ViewBag property to the same name as a model property, and got the above mentioned error message (when getting the view though, not posting).

In essence I had set the following in the controller:

ViewBag.TermsAndConditions = "blah blah blah"

and in my model I had:

public bool TermsAndConditions { get; set; }

The line @Html.CheckBoxFor(m => m.TermsAndConditions) threw and error from the view.

Renaming either the ViewBag or model property fixed it, obviously.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号