【问题标题】:How to fire custom validation attribute before executes action in MVC?如何在 MVC 中执行操作之前触发自定义验证属性?
【发布时间】:2013-11-26 19:13:43
【问题描述】:

我有一个自定义 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;
    }
}

好的,当我在我的视图中使用 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");
    }

【问题讨论】:

  • 验证属性总是在Action之前执行。您可能在控制器中做错了什么。请发布您的操作和视图的代码。
  • @ataravati Ive 编辑 OP,谢谢
  • AddDocument 操作是否应该将您的模型传递给 EditorTemplate?为什么要使用 ViewData?您甚至没有将模型传递给您的视图。
  • @ataravati 我使用 viewdata 在 AddDocument 视图中绑定一个网格
  • 您正在使用 ViewData 将模型传递给您的视图?那是大错特错了。 ViewData 应该用于传递不属于您的模型的少量额外数据。数据注释属性创建的验证规则不会那样工作。那么您的 EditorTemplate 使用的是什么模型?

标签: c# asp.net-mvc validation asp.net-mvc-4


【解决方案1】:

如果您想使用客户端验证,这个post 看起来像是您问题的答案。

如果这不是您想要的,您还可以查看OnActionExecuting() method,它在控制器中的操作方法之前执行

【讨论】:

  • 这不是问题的直接答案。它应该作为评论发布。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-19
  • 1970-01-01
  • 2014-05-26
  • 2019-03-13
  • 1970-01-01
相关资源
最近更新 更多