MVC Remote Validation With Additional bool Fields

后端 未结 1 1967
别那么骄傲
别那么骄傲 2020-12-21 21:39

I am trying to use Remote Validation with an additional bool checkbox field

[Remote(\"IsStorageConnectionValid\", \"TenantManagement\", AdditionalFields = \"         


        
相关标签:
1条回答
  • 2020-12-21 21:48

    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

    0 讨论(0)
提交回复
热议问题