Asp.net mvc 5 当用户勾选复选框时,值的复选框不会更改
我有一个用于JQuery表单并绑定到我的模型的复选框,我的问题是,当用户选中或取消选中复选框时,用于某些客户端验证的值总是true,用于服务器端验证的值总是false。为什么我的复选框不更新值 查看:Asp.net mvc 5 当用户勾选复选框时,值的复选框不会更改,asp.net-mvc-5,checkboxfor,Asp.net Mvc 5,Checkboxfor,我有一个用于JQuery表单并绑定到我的模型的复选框,我的问题是,当用户选中或取消选中复选框时,用于某些客户端验证的值总是true,用于服务器端验证的值总是false。为什么我的复选框不更新值 查看: <form id="companyForm"> <fieldset> <p> @Html.LabelFor(model => model.allCompany, new { @checked = "chec
<form id="companyForm">
<fieldset>
<p>
@Html.LabelFor(model => model.allCompany, new { @checked = "checked" })
@Html.CheckBoxFor(model => model.allCompany)
</p>
<p>
@Html.LabelFor(model => model.hierarchyValidation)
@Html.DisplayFor(model => model.hierarchyValidation)
@Html.HiddenFor(model => model.hierarchyValidation)
@Html.ValidationMessageFor(model => model.hierarchyValidation)
</p>
<!-- Allow form submission with keyboard without duplicating the dialog button -->
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
var isApplicationValid = $('#application').valid();
var isHierarchyValid = $('#hierarchyValidation').valid();
if (isHierarchyValid && isCompanyValid) {
var roleName = $("#roleName").val();
var hierarchy = $("#hierarchyValidation").val().toString();
var data = {
"reasons": message,
"hierarchyValidation": hierarchy
};
$.ajax({
url: url,
type: "POST",
data: data,
success: function (data, textStatus, jqXHR) {
alert("Success");
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error");
}
});
}
}
public enum Comparison
{
IsEmpty,
ContainsValue
}
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class IsEmptyAttribute : ValidationAttribute, IClientValidatable
{
private const string DefaultErrorMessage = "{0} Is required if a value from {1} is not selected.";
public string ValueLabel { get; private set; }
public string CompaniesValue { get; set; }
public IsEmptyAttribute(string valueLabel, string companiesValue)
: base(DefaultErrorMessage)
{
if (string.IsNullOrEmpty(valueLabel))
{
throw new ArgumentNullException("otherProperty");
}
ValueLabel = valueLabel;
CompaniesValue = companiesValue;
}
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, ValueLabel, CompaniesValue);
}
protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
var allCompaniesSelected = validationContext.ObjectInstance.GetType()
.GetProperty(CompaniesValue);
var allCompaniesSelectedValue = allCompaniesSelected
.GetValue(validationContext.ObjectInstance, null);
if (Convert.ToBoolean(allCompaniesSelectedValue) == false)
{
if (value == null)
{
return new ValidationResult(
FormatErrorMessage(validationContext.DisplayName));
}
}
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var clientValidationRule = new ModelClientValidationRule()
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "isempty"
};
clientValidationRule.ValidationParameters.Add("companiesvalue", CompaniesValue);
return new[] { clientValidationRule };
}
}
(function ($) {
$.validator.addMethod("isempty", function (value, element, params) {
if (this.optional(element)) {
var allCompanies = $('#addRoleCompany_allCompany')
if (allCompanies.val() == false) {
var otherProp = $('#addRoleCompany_' + params)
return (otherProp.val() != value);
}
}
return true;
});
$.validator.unobtrusive.adapters.addSingleVal("isempty", "otherproperty");
}(jQuery));
客户端验证:
<form id="companyForm">
<fieldset>
<p>
@Html.LabelFor(model => model.allCompany, new { @checked = "checked" })
@Html.CheckBoxFor(model => model.allCompany)
</p>
<p>
@Html.LabelFor(model => model.hierarchyValidation)
@Html.DisplayFor(model => model.hierarchyValidation)
@Html.HiddenFor(model => model.hierarchyValidation)
@Html.ValidationMessageFor(model => model.hierarchyValidation)
</p>
<!-- Allow form submission with keyboard without duplicating the dialog button -->
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
var isApplicationValid = $('#application').valid();
var isHierarchyValid = $('#hierarchyValidation').valid();
if (isHierarchyValid && isCompanyValid) {
var roleName = $("#roleName").val();
var hierarchy = $("#hierarchyValidation").val().toString();
var data = {
"reasons": message,
"hierarchyValidation": hierarchy
};
$.ajax({
url: url,
type: "POST",
data: data,
success: function (data, textStatus, jqXHR) {
alert("Success");
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error");
}
});
}
}
public enum Comparison
{
IsEmpty,
ContainsValue
}
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class IsEmptyAttribute : ValidationAttribute, IClientValidatable
{
private const string DefaultErrorMessage = "{0} Is required if a value from {1} is not selected.";
public string ValueLabel { get; private set; }
public string CompaniesValue { get; set; }
public IsEmptyAttribute(string valueLabel, string companiesValue)
: base(DefaultErrorMessage)
{
if (string.IsNullOrEmpty(valueLabel))
{
throw new ArgumentNullException("otherProperty");
}
ValueLabel = valueLabel;
CompaniesValue = companiesValue;
}
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, ValueLabel, CompaniesValue);
}
protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
var allCompaniesSelected = validationContext.ObjectInstance.GetType()
.GetProperty(CompaniesValue);
var allCompaniesSelectedValue = allCompaniesSelected
.GetValue(validationContext.ObjectInstance, null);
if (Convert.ToBoolean(allCompaniesSelectedValue) == false)
{
if (value == null)
{
return new ValidationResult(
FormatErrorMessage(validationContext.DisplayName));
}
}
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var clientValidationRule = new ModelClientValidationRule()
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "isempty"
};
clientValidationRule.ValidationParameters.Add("companiesvalue", CompaniesValue);
return new[] { clientValidationRule };
}
}
(function ($) {
$.validator.addMethod("isempty", function (value, element, params) {
if (this.optional(element)) {
var allCompanies = $('#addRoleCompany_allCompany')
if (allCompanies.val() == false) {
var otherProp = $('#addRoleCompany_' + params)
return (otherProp.val() != value);
}
}
return true;
});
$.validator.unobtrusive.adapters.addSingleVal("isempty", "otherproperty");
}(jQuery));
自定义验证程序属性:
<form id="companyForm">
<fieldset>
<p>
@Html.LabelFor(model => model.allCompany, new { @checked = "checked" })
@Html.CheckBoxFor(model => model.allCompany)
</p>
<p>
@Html.LabelFor(model => model.hierarchyValidation)
@Html.DisplayFor(model => model.hierarchyValidation)
@Html.HiddenFor(model => model.hierarchyValidation)
@Html.ValidationMessageFor(model => model.hierarchyValidation)
</p>
<!-- Allow form submission with keyboard without duplicating the dialog button -->
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
var isApplicationValid = $('#application').valid();
var isHierarchyValid = $('#hierarchyValidation').valid();
if (isHierarchyValid && isCompanyValid) {
var roleName = $("#roleName").val();
var hierarchy = $("#hierarchyValidation").val().toString();
var data = {
"reasons": message,
"hierarchyValidation": hierarchy
};
$.ajax({
url: url,
type: "POST",
data: data,
success: function (data, textStatus, jqXHR) {
alert("Success");
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error");
}
});
}
}
public enum Comparison
{
IsEmpty,
ContainsValue
}
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class IsEmptyAttribute : ValidationAttribute, IClientValidatable
{
private const string DefaultErrorMessage = "{0} Is required if a value from {1} is not selected.";
public string ValueLabel { get; private set; }
public string CompaniesValue { get; set; }
public IsEmptyAttribute(string valueLabel, string companiesValue)
: base(DefaultErrorMessage)
{
if (string.IsNullOrEmpty(valueLabel))
{
throw new ArgumentNullException("otherProperty");
}
ValueLabel = valueLabel;
CompaniesValue = companiesValue;
}
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, ValueLabel, CompaniesValue);
}
protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
var allCompaniesSelected = validationContext.ObjectInstance.GetType()
.GetProperty(CompaniesValue);
var allCompaniesSelectedValue = allCompaniesSelected
.GetValue(validationContext.ObjectInstance, null);
if (Convert.ToBoolean(allCompaniesSelectedValue) == false)
{
if (value == null)
{
return new ValidationResult(
FormatErrorMessage(validationContext.DisplayName));
}
}
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var clientValidationRule = new ModelClientValidationRule()
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "isempty"
};
clientValidationRule.ValidationParameters.Add("companiesvalue", CompaniesValue);
return new[] { clientValidationRule };
}
}
(function ($) {
$.validator.addMethod("isempty", function (value, element, params) {
if (this.optional(element)) {
var allCompanies = $('#addRoleCompany_allCompany')
if (allCompanies.val() == false) {
var otherProp = $('#addRoleCompany_' + params)
return (otherProp.val() != value);
}
}
return true;
});
$.validator.unobtrusive.adapters.addSingleVal("isempty", "otherproperty");
}(jQuery));
有谁能告诉我应该在哪里找到问题,问题是什么
感谢您对此问题的帮助。事实证明,我忽略了一个事实,即在检查复选框是否勾选后,需要从Jquery传递值
一个简单的错误。感谢所有帮助我解决此问题的人。生成的复选框的
值
属性为真
,其关联的隐藏输入为假
(这样它就可以正确地绑定到后面的布尔值)。当我尝试进行数据验证时,值总是假的,这是什么意思?@StephenMuecke抱歉,我在问题中没有把问题说得太清楚,我现在已经编辑了它。我使用的表单有一个multiselect,如果复选框为false,则需要该复选框。但是,当我尝试验证客户端时,客户端总是正确的,而服务器端总是错误的。如何验证客户端显示您的代码。而allCompany
的值将是true
或false
(服务器端),这取决于复选框是否被选中(除非您禁用了复选框)@StephenMuecke我只是使用jquery:var-isHierarchyValid=$('addrolecocompany\u hierarchyValidation')。valid()代码>一旦我简化了解决方案,我将添加完整的代码。嗨@StephenMuecke,我已经添加了我一直在使用的代码的简化版本,我已经得到了编译。我的自定义验证器就是我现在怀疑出现问题的地方。谢谢你能给我的任何帮助和建议。