【问题标题】:With ASP.NET MVC, how to display errors when outside controller?使用 ASP.NET MVC,如何在控制器外部显示错误?
【发布时间】:2017-05-07 14:42:29
【问题描述】:

我正在尝试在我的代码中的任何位置轻松地在我的视图中显示错误:

@Html.ValidationSummary("", new { @class = "text-danger" })

在 MVC 之前,我使用过:

ValidationError.Display("My error message");

我的ValidationError 类看起来像这样:

public class ValidationError : IValidator
{
    private ValidationError(string message)
    {
        ErrorMessage = message;
        IsValid = false;
    }

    public string ErrorMessage { get; set; }
    public bool IsValid { get; set; }

    public void Validate()
    {
        // no action required
    }

    public static void Display(string message)
    {
        // here is the only part I would like to change ideally
        var currentPage = HttpContext.Current.Handler as Page;                
        currentPage.Validators.Add(new ValidationError(message));
    }

}

现在使用 MVC,要添加错误,我不能使用 currentPage.Validators。 我需要使用ModelState,但我的问题是当我不在控制器中时无法访问ModelState。我尝试通过HttpContext 访问控制器或ModelState,但我还没有找到方法。有什么想法吗?

ModelState.AddModelError("", "My error message");

【问题讨论】:

  • 你有能力修改你的模型和视图吗?
  • 对视图来说是的,但我不想修改模型,我认为解决方案会变得过于“繁重/复杂”
  • 那么你能修改ValidationError类吗?顺便说一句,IValidator 来自哪里?
  • 是的,我可以,我的目标是理想情况下只修改 ValidationError 类,IValidator 来自使用 System.Web.UI;
  • 我认为您的问题需要一些更新 :) 您如何在 ASP.Net MVC 中实际使用 ValidationError ?向我们展示一个使用它的操作。是否有必要总是 ValidationError 或者我们可以摆脱它?

标签: asp.net-mvc


【解决方案1】:

1。您可以通过ViewContext.ViewData.ModelState 访问它。然后使用

@if (!ViewContext.ViewData.ModelState.IsValid)
{
    <div>There are some errors</div>
}

ViewData.ModelState.IsValidField("NameOfInput")

获取输入列表:

var errors = ViewData.ModelState.Where(n => n.Value.Errors.Count > 0).ToList();

2。您可以像这样传递模型状态:

public class MyClass{
    public static void errorMessage(ModelStateDictionary ModelState) {
        if (something) ModelState.AddModelError("", "Error Message");
    }
}

在控制器中使用:

MyClass.errorMessage(ModelState);

在视图中使用:

MyClass.errorMessage(ViewContext.ViewData.ModelState.IsValid);

3。 ModelState 通过ActionFilter

public class ValidateModelAttribute : ActionFilterAttribute
{
     public override void OnActionExecuting(ActionExecutingContext filterContext)
     {
          if (filterContext.Controller.ViewData.ModelState.IsValid)
          {
                //Do Something 
          }
     }
}

您可以通过thisthis 链接获得更多帮助。

【讨论】:

  • 谢谢...我试过了,但 ViewData 只能在 Controller 或 View 中访问,在外部时无法访问(例如:负责导入某些数据的自定义类)。我认为一种解决方法是将 ModelState 传递给 Constructor 中的那个类,但我希望让它更简单。
  • @JohnMarston 我更新了我的答案。你能试试吗?
  • 感谢更新的答案...确实可以,但我的目标是避免传递 ModelState 并通过 HttpContext 或类似的方式获取它,但这可能是不可能的...听起来可能挑剔,但想象你有 300 次调用 .errorMessage() 来更改:P 我将你的答案标记为有用,因为它可以用作解决方法
猜你喜欢
  • 1970-01-01
  • 2010-11-24
  • 2022-06-16
  • 2017-09-19
  • 2013-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多