I am trying to use Remote Validation with an additional bool checkbox field
[Remote("IsStorageConnectionValid", "TenantManagement", AdditionalFields = "CreateStorage")]
public String StorageConnectionString { get; set; }
Validation code
public JsonResult IsStorageConnectionValid(string storageConnectionString, bool createStorage){
It works perfectly in terms of it hitting the validator. However createStorage is always true irrespective of the value of the checkbox. If I use additional fields that aren't check boxes they are supplied perfectly.
Checkbox created as standard:
@Html.CheckBoxFor(m => m.CreateStorage)
Is this a bug? Or am I doing it wrong?
It does appear that this is a bug when used with
@Html.CheckBoxFor
. The problem is thatCheckBoxFor
renders 2 elements, a checkbox withvalue="true"
and a hidden input withvalue="false"
(Unchecked checkboxes do not post back so the second hidden input ensures a value is posted back for use by theDefaultModelBinder
)Looking at the relevant section of the
jquery.validate.unobtrusive.js
filethe
return
statement returns (in your case).find(':input[name="CreateStorage"]').val();
which returns the value of the first input with thename="CreateStorage"
which will always betrue
(the value of the checkbox)As a test, if you render the value using
HiddenFor
rather thatCheckBoxFor
you will receive the correct value in yourIsStorageConnectionValid
method (but of course this does help since you cant change the value)Not sure of the best solution, but the
unobtrusive
script should be first checking if.find(..)
returns more than one element, then if the first is a checkbox which is unchecked, returning the value of the second element.Edit
I have reported this as an issue at Codeplex
Edit 2
I have been advised the the issue has now been fixed here