MVC Remote Validation With Additional bool Fields
Asked Answered
C

1

1

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?

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

Colloquialism answered 10/10, 2014 at 22:17 Comment(2)
It might help for us to see the code as the browser sees it. In other words, please post a concise example of the rendered HTML markup and JavaScript.Jehovist
Added Fiddle. It does the same thingColloquialism
C
5

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

Craquelure answered 10/10, 2014 at 23:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.