Please explain Html.CheckBoxFor() rendering

J

J055

Hi

When I use this:

<%= Html.CheckBoxFor(m => m.CopyAddress)%>

it produces html like:

<input checked="checked" id="CopyAddress"
name="CopyAddress" type="checkbox" value="true" /><input name="CopyAddress"
type="hidden" value="false" />

or

<input id="CopyAddress" name="CopyAddress"
type="checkbox" value="true" /><input name="CopyAddress" type="hidden"
value="false" />

which means the System.Web.Mvc.FormCollection for value CopyAddress are
either "false" or "true,false".

Can someone explain the logic and provide an example of how to use it to get
either a true or false value?

Thanks
Andrew
 
G

Guest

Hi

When I use this:

<%= Html.CheckBoxFor(m => m.CopyAddress)%>

it produces html like:

                    <input checked="checked" id="CopyAddress"
name="CopyAddress" type="checkbox" value="true" /><input name="CopyAddress"
type="hidden" value="false" />

or

                    <input id="CopyAddress" name="CopyAddress"
type="checkbox" value="true" /><input name="CopyAddress" type="hidden"
value="false" />

which means the System.Web.Mvc.FormCollection for value  CopyAddress are
either "false" or "true,false".

Can someone explain the logic and provide an example of how to use it to get
either a true or false value?

Thanks
Andrew

Please check this thread
http://forums.asp.net/t/1314753.aspx
 
J

J055

Thanks

Rendering a dumb hidden field for every checkbox is a messy business. I
guess if model binding requires it then so be it. I'm not using model
binding at the moment so I created this function to handle bool values in
the FormCollection when using Html.CheckBoxFor.

private static bool CoerceToBool(string s)
{
if (string.IsNullOrEmpty(s)) return false;

var a = s.Split(',');
foreach (string t in a)
{
bool value;
if (bool.TryParse(t, out value) && value) return true;
}
return false;
}

Cheers
Andrew
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top