我已经为单个属性进行了客户端验证,但是,我想使用客户端验证在模型级别(2 个或更多属性)进行验证。
我@Html.ValidationSummary(true)
用来显示我创建的 Model 属性的验证错误。
但是,当生成模型错误时,它不会显示消息。它会阻止执行操作,但不会显示错误。
有人知道为什么会这样吗?
我的预感是它与客户端验证有关,因为在这种情况下服务器端不起作用,因为我必须使用 Ajax 表单。
任何意见,将不胜感激!
模型属性
public class AuditDetailValidatorAttribute : ValidationAttribute, IClientValidatable
{
public AuditDetailValidatorAttribute()
{
ErrorMessage = "Must select an NCN level...";
}
public override bool IsValid(object value)
{
AuditRequirementDetail audit = value as AuditRequirementDetail;
if (audit == null || audit.AuditResult.Id == 0 || audit.AssessmentLevel.Id == 0)
{
return true;
}
else
{
return !(audit.AuditResult.Id == 4 && audit.AssessmentLevel.Id == 1);
}
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
return new List<ModelClientValidationRule>
{
new ModelClientValidationRule
{
ValidationType = "required",
ErrorMessage = this.ErrorMessage
}
};
}
}
模型类
[AuditDetailValidator]
public class AuditRequirementDetail
{
// Constructor
public AuditRequirementDetail()
{
// instantiate the contained objects on AuditRequirementDetail creation
AssessmentLevel = new AssessmentLevel();
AuditResult = new AuditResult();
Requirement = new RequirementDetail();
Attachment = new Attachment();
Counter = 0;
}
/* rest of the code */
}
看法
@model pdiqc.Models.AuditRequirement.AuditRequirementDetail
@{
var SuccessTarget = "success" + Model.DetailID;
var IsValidTarget = "IsValid" + Model.DetailID;
var PerformCompletedTarget = "PerformCompleted" + Model.DetailID;
var AuditResultTarget = "AuditResult_Id" + Model.DetailID;
var AssessmentLevelTarget = "AssessmentLevel_Id" + Model.DetailID;
var DesignatorTarget = "Designator_Id" + Model.DetailID;
var EvidenceTarget = "Evidence_Id" + Model.DetailID;
var AttachmentTarget = "Attachments_Id" + Model.DetailID;
var AuditResultReferral = "#" + AuditResultTarget;
var AssessmentLevelReferral = "#" + AssessmentLevelTarget;
var DesignatorReferral = "#" + DesignatorTarget;
var EvidenceReferral = "#" + EvidenceTarget;
var AttachmentReferral = "#" + AttachmentTarget;
}
@using (Ajax.BeginForm("PerformRequirement", "Audit", new AjaxOptions { HttpMethod = "POST", OnSuccess = "success" }, new {Class="PerformReqForm" }))
{
@Html.ValidationSummary(true)
if ((Model.AuditResult.Id == 1 && Model.AssessmentLevel.Id > 1) || Model.Evidence == string.Empty || Model.Evidence == null)
{
<input class="@IsValidTarget" name="IsValid" type="hidden" value=false />
}
else
{
<input class="@IsValidTarget" name="IsValid" type="hidden" value=true />
}
<p class="reqText">@Model.RequirementLabel.ConfigurableLabelDesc #@ViewBag.PerformCounter - @ModelMetadata.FromLambdaExpression(x => x.Requirement.Text, ViewData).SimpleDisplayText</p>
<div class="hide">
/* REST OF CODE */
}