Remote MVC check with additional bool fields

I am trying to use Remote Validation with an extra bool check box

[Remote("IsStorageConnectionValid", "TenantManagement", AdditionalFields = "CreateStorage")] public String StorageConnectionString { get; set; } 

confirmation code

 public JsonResult IsStorageConnectionValid(string storageConnectionString, bool createStorage){ 

It works great in terms of clicking on the validator. However, createStorage is always true regardless of the value of the flag. If I use extra fields that are not checkboxes, they are delivered fine.

Flag created as standard:

  @Html.CheckBoxFor(m => m.CreateStorage) 

This is mistake? Or am I doing it wrong?

Fiddle Is here (I think MVC4, but does the same)

+1
source share
1 answer

This seems to be a bug when used with @Html.CheckBoxFor . The problem is that CheckBoxFor displays 2 elements, a checkbox with value="true" and hidden input with value="false" (checkboxes marked "Not checked" are not returned, so the second hidden input ensures that the value is sent back for use DefaultModelBinder )

Looking at the appropriate 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 returns (in your case) .find(':input[name="CreateStorage"]').val(); which returns the first value with name="CreateStorage" , which will always be true (checkbox value)

As a test, if you use the HiddenFor value instead of CheckBoxFor , you will get the correct value in the IsStorageConnectionValid method (but of course this helps, since you cannot change the value)

Not sure of the best solution, but an unobtrusive script should first check to see if .find(..) returns more than one element, and if the first flag that is not set returns the value of the second element.

Edit

I reported this as a problem in Codeplex

Edit 2

I was informed that the problem is now fixed here

+5
source

All Articles