簡體   English   中英

如何在MVC中執行動作之前觸發自定義驗證屬性?

[英]How to fire custom validation attribute before executes action in MVC?

我有一個自定義的CNPJ屬性類,以在模型類中驗證特定的屬性。

[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;
    }
}

好的,當我在視圖中使用空的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");
    }

如果您要使用客戶端驗證,則此帖子看起來像是您問題的答案。

如果這不是您想要的,還可以查看OnActionExecuting()方法 ,該方法在控制器中的action方法之前執行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM