简体   繁体   中英

Html.CheckBox returning value not true/false

This seems ridicouous but can you only return true/false from an MVC checkbox? I remember back in the day (in classic asp) it was perfectly valid to return a value from a ticked checkbox but Microsoft appears to of decided that checkboxes should only contain true/false value.

So if you add the following:

@Html.CheckBox("PropertyTypes", true, new {@value="A"})

I would expect my form POST to contain Property=A , what I end up with is Property=A&Property=true which then breaks the model so I get a null in the property rather than the string I wanted.

On investigation it turns out this is because microsoft adds an extra input for so I get a false if I don't want to check the input ...gee thanks a lot......:/

<input id="PropertyTypes" type="checkbox" value="Hotel" name="PropertyTypes" data-val-youmustselectatleastone="You must select at least one Property Type" data-val="true" checked="checked">
<input type="hidden" value="false" name="PropertyTypes">

WHY!

I could just code in an input myself just using flat HTML but then I loose all my unobtrusive validation.

any ideas on how to get around this stupidity?

Ps the number of checkboxes is dynamic so adding a property for each value isn't going to cut it.

This seems ridicouous but can you only return true/false from an MVC checkbox?

I don't find it ridiculous. When you give it a second thought modeling a checked/unchecked state with a boolean variable actually makes sense.

WHY!

Because that's how the designers of the framework decided to implement the CheckBox helper.

any ideas on how to get around this stupidity?

By using a view model of course:

public class MyViewModel
{
    public int Id { get; set; }
    public bool IsChecked { get; set; }
}

and then assuming you had a collection of those you would use a checkbox and a hidden field to store the corresponding id of the item:

@Html.HiddenFor(x => x.SomeCollection[i].Id)
@Html.CheckBoxFor(x => x.SomeCollection[i].IsChecked)

When the form is submitted you will get the collection property containing the ids of your items and whether they were selected or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM