我正在尝试强制视图的必需条款和条件复选框。我按照这个论坛上列出的代码示例:http://www.dotnet-tricks.com/Tutorial/mvc/8UFa191212-Custom-Validation-for-Checkbox-in-MVC-Razor.html但是如果我在IsValid方法中设置断点,它是否永远不会到达。此外,ModelState.IsValid应为false时返回true;如果从未选中该复选框。
以下是ViewModel的代码:
public class TermsConditionViewModel
{
[MustBeTrue(ErrorMessage = "The terms and conditions must be read and agreed to complete the registration process.")]
[Display(Name = "")]
public bool TermsConditionsCompleted { get; set; }
}
以下是自定义数据注释的代码:
public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable // IClientValidatable for client side Validation
{
public override bool IsValid(object value)
{
return value is bool && (bool)value;
}
// Implement IClientValidatable for client side Validation
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
return new ModelClientValidationRule[] { new ModelClientValidationRule { ValidationType = "checkbox", ErrorMessage = this.ErrorMessage } };
}
}
public class MustBeSelected : ValidationAttribute, IClientValidatable // IClientValidatable for client side Validation
{
public override bool IsValid(object value)
{
if (value == null || (int)value == 0)
return false;
else
return true;
}
// Implement IClientValidatable for client side Validation
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
return new ModelClientValidationRule[] { new ModelClientValidationRule { ValidationType = "dropdown", ErrorMessage = this.ErrorMessage } };
}
}
这是客户端验证的javascript代码
$.validator.unobtrusive.adapters.add("dropdown", function (options) {
// debugger;
if (options.element.tagName.toUpperCase() == "SELECT" && options.element.type.toUpperCase() == "SELECT-ONE") {
options.rules["required"] = true;
if (options.message) {
options.messages["required"] = options.message;
}
}
});
$.validator.unobtrusive.adapters.add("checkbox", function (options) {
if (options.element.tagName.toUpperCase() == "INPUT" && options.element.type.toUpperCase() == "CHECKBOX") {
options.rules["required"] = true;
if (options.message) {
options.messages["required"] = options.message;
}
}
});
这是生成的标记
<input data-val="true" data-val-checkbox="The terms and conditions must be read and agreed to complete the registration process." data-val-required="The field is required." id="TermsConditionsCompleted" name="TermsConditionsCompleted" type="checkbox" value="true" /><input name="TermsConditionsCompleted" type="hidden" value="false" /> I have read and agree with the terms and conditions described above
是否需要进行额外配置才能实现此功能?到目前为止,我发现的所有示例似乎都以相同的方式设置,Web.Config,Global.asax等中没有配置。
你错过了一些jQuery验证步骤。我已经解决了同样的问题,并按照此链接的路径完成了相同的任务:http://www.yogihosting.com/client-side-validation-asp-net-mvc/
希望它能帮到你。
亚历山德罗
你的解决方案看起来真的有点过头了,而我只是在表单提交上添加一个jQuery方法,确保选中复选框。
更少的代码。