我有一个自定义CNPJ属性类来验证我的模型类中的speciefic属性。
[Required]
[CNPJ(ErrorMessage = "Invalid input")]
public string SupplierIdentification { get; set; }
我的CNPJ属性类:
public class CNPJAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
var cnpj = Convert.ToString(value);
if (SessionCompanyRepository.ValidaCnpj(cnpj))
{
return ValidationResult.Success;
}
else
{
var errorMessage = FormatErrorMessage(validationContext.DisplayName);
return new ValidationResult(errorMessage);
}
}
return ValidationResult.Success;
}
}
好的,当我在我的视图中使用null SupplierIdentification提交时,甚至在调用提交按钮的操作之前,[Required]就会触发。当我放置一些无效的SupplierIdentification时,将触发该操作并且(ModelState.IsValid)检查CNPJAttribute结果。我想在执行操作之前触发[CNPJ]属性类,如[Required]属性。
连连呢? 感谢。
编辑: 我的“根”观点:
@(Html.Telerik()
.Grid<DocumentModel>()
.BindTo((List<DocumentModel>)ViewData["documents"])
.Name("DocumentGrid").EnableCustomBinding(true)
.DataBinding(x =>
x.Server()
.Insert("InsertDocument", "Client")
.Delete("DeleteTempDocument", "Client"))
.DataKeys(a => a.Add(c => c.IDDocument)
.RouteKey("idDocument"))
.Editable(a => a.Mode(GridEditMode.InForm)
.TemplateName("AddDocumentModel")
.InsertRowPosition(GridInsertRowPosition.Top))
.ToolBar(commands => commands.Insert().Text("Add Document"))
.Columns(c =>
{
c.Bound(column => column.IDDocument).Visible(false);
c.Bound(column => column.SupplierIdentification);
c.Bound(column => column.SupplierName);
c.Command(command => command.Delete());
}))
我在EditorTemplate文件夹中的视图:
@using (Html.BeginForm())
{
@Html.HiddenFor(m => m.IDDocument)
<b>@Html.Label("CPF/CNPJ:")</b>
<div>
@Html.TextBoxFor(m => m.SupplierIdentification)
@Html.ValidationMessageFor(a => a.SupplierIdentification)
<b>@Html.Label("Razão Social:")</b>
<div>
@Html.TextBoxFor(m => m.SupplierName)
@Html.ValidationMessageFor(a => a.SupplierName)
}
我的控制员:
public ActionResult InsertDocument(DocumentModel model)
{
if (ModelState.IsValid)
{
if (System.Web.HttpContext.Current.Session["Documents"] == null)
{
ViewData["documents"] =
System.Web.HttpContext.Current.Session["Documents"] = new List<DocumentModel>();
}
model.IDDocument = Util.IDDocument;
DocumentSessionRepository.Insert(model);
ViewData["documents"] = DocumentSessionRepository.AllDocuments();
return RedirectToAction("AddDocument");
}
return RedirectToAction("AddDocument");
}
答案 0 :(得分:2)
如果您想使用客户端验证,此post看起来像是您问题的答案。
如果这不是您想要的,您还可以查看OnActionExecuting() method,它在控制器中的操作方法之前执行