B.McCarthy
B.McCarthy

Reputation: 123

asp.net mvc how to bind to an empty checkbox value?

I am modifying an existing asp.net mvc application that creates a list of checkboxes from a list on the model, with property name "MyModelProperty" and additionally generates one more input element for "Select All" which has the following html:

<input name="MyModelProperty_SelectAll" type="checkbox" CHECKED="checked" value=""/>

What is the property declaration in the model that would create a boolean property that would bind to this existing element in the view?

I tried, 'public bool MyModelProperty_SelectAll {get;set;}' but it was returning null. Is that because the value is an empty string in the html input control?

Upvotes: 0

Views: 2103

Answers (2)

Fals
Fals

Reputation: 6839

Change your Model property for string:

public string MyModelProperty_SelectAll { get; set; }

Set some value for the checkbox, then in the server, if its checked, the value will be the given value, else you will see null.

<input name="MyModelProperty_SelectAll" type="checkbox" value="all"/>

EDIT:

If you want to bind this to a bool, you must provide a value="true" and a hidden field:

<input class="input-validation-error" id="MyModelProperty_SelectAll" name="MyModelProperty_SelectAll" type="checkbox" value="true">
<input name="MyModelProperty_SelectAll" type="hidden" value="false">

This example code above was generated using the Html.CheckBox helper.

Upvotes: 2

MRB
MRB

Reputation: 3812

If you don't use MVC htmlhelpers for generating checkboxes you must add an additional hidden element for your checkbox:

<input name="MyModelProperty_SelectAll" type="checkbox" value="true"/>
<input name="MyModelProperty_SelectAll" type="hidden" value="true"/>

Upvotes: 2

Related Questions