1
我想驗證mvc5中所需的複選框。在大多數情況下,其驗證/工作...我的問題是其不觸發ErrorMessage。換句話說,它阻止我提交時未檢查,但沒有顯示請接受條款&條件爲其應該。ASP.NET MVC 5 - 用於驗證複選框的自定義屬性
我下面
自定義屬性代碼驗證複選框
namespace Checkboxtest.Models
{
//Making Custom attribute for validating checkbox
// IClientValidatable for client side Validation
public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable
{
public override bool IsValid(object value)
{
return value != null && 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 = "checkboxtrue", ErrorMessage = this.ErrorMessage } };
}
}
}
域模型
[Display(Name = "Terms and Conditions")]
[MustBeTrue(ErrorMessage = "Please Accept the Terms & Conditions")]
public bool TermsAndConditions { get; set; }
複選框形式
@using (Html.BeginForm())
{
<div class="form-group">
@Html.CheckBoxFor(x => x.TermsAndConditions)
@Html.LabelFor(x => x.TermsAndConditions)
@Html.ValidationMessageFor(x => x.TermsAndConditions)
</div>
<button type="submit" class="btn btn-success submit">Submit</button>
}
任何人都可以讓我知道了什麼我做錯了?謝謝!
你已經加入這個佈局? @ Scripts.Render(「〜/ bundles/jquery」) @ Scripts.Render(「〜/ bundles/jqueryval」) – Johan