It does appear that this is a bug when used with @Html.CheckBoxFor
. The problem is that CheckBoxFor
renders 2 elements, a checkbox with value="true"
and a hidden input with value="false"
(Unchecked checkboxes do not post back so the second hidden input ensures a value is posted back for use by the DefaultModelBinder
)
Looking at the relevant section of the jquery.validate.unobtrusive.js
file
adapters.add("remote", ["url", "type", "additionalfields"], function (options) {
var value = {
url: options.params.url,
type: options.params.type || "GET",
data: {}
},
prefix = getModelPrefix(options.element.name);
$.each(splitAndTrim(options.params.additionalfields || options.element.name), function (i, fieldName) {
var paramName = appendModelPrefix(fieldName, prefix);
value.data[paramName] = function () {
return $(options.form).find(":input[name='" + escapeAttributeValue(paramName) + "']").val();
};
});
setValidationValues(options, "remote", value);
});
the return
statement returns (in your case) .find(':input[name="CreateStorage"]').val();
which returns the value of the first input with the name="CreateStorage"
which will always be true
(the value of the checkbox)
As a test, if you render the value using HiddenFor
rather that CheckBoxFor
you will receive the correct value in your IsStorageConnectionValid
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