运行页面时,范围上的验证会显示所需的错误但会忽略true true和false false会在勾选复选框时返回错误消息,无论范围设置为什么。 例如,当范围设置为true并勾选复选框时,它会给出一条错误消息,当它没有勾选时,它允许我继续没有错误。当range为false时,它的行为完全相同。
未勾选时应该出错
<p>
Please confirm you have read the <a href="~/Downloads/AccreditationAndSTCompanyEligibility.pdf" target="_blank">eligibility document.</a>
@Html.CheckBoxFor(m => m.ConfirmEligibilityDocument)
@Html.ValidationMessageFor(m => m.ConfirmEligibilityDocument)
</p>
[Range(typeof(bool), "true", "true", ErrorMessage = "You must accept our Terms & Conditions.")]
public bool ConfirmEligibilityDocument { get; set; }
答案 0 :(得分:0)
请尝试用
替换您的范围属性[MustBeTrue(ErrorMessage = "You must accept our Terms & Conditions")]
您将需要该
的自定义属性[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class MustBeTrueAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
return value != null && value is bool && (bool)value;
}
}
此解决方案提供了in this article
我不知道你的ptoject是如何设置的,但这是我的测试代码,它完美无缺
- Index.chtml
@using (Html.BeginForm())
{ @ Html.ValidationSummary(真)
<p>please confirm that you have...</p>
@Html.CheckBoxFor(m => m.ConfirmEligibilityDocument)
@Html.ValidationMessageFor(m => m.ConfirmEligibilityDocument)
<input type="submit" value="submit"/>
}
- HomeController.cs
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
var t = new TestBool();
return View();
}
[HttpPost]
public ActionResult Index(TestBool t)
{
return View("Index",t);
}
}
- TestBoll.cs - 这是我的模型
public class TestBool
{
[MustBeTrue(ErrorMessage = "Must be accepted")]
public bool ConfirmEligibilityDocument { get; set; }
}
- MustBeTrueAttribute.cs - 这是属性类
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class MustBeTrueAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
return value != null && value is bool && (bool)value;
}
}