gpt4 book ai didi

asp.net-mvc - 使用 ASP.NET MVC,如何在外部 Controller 时显示错误?

转载 作者:行者123 更新时间:2023-12-04 21:06:47 24 4
gpt4 key购买 nike

我正在尝试使用以下方法从代码中的任何位置轻松显示我的 View 中的错误:

@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当我不在 Controller 中时 .我尝试访问 Controller 或 ModelState通过 HttpContext但我还没有找到办法做到这一点。任何的想法 ?
ModelState.AddModelError("", "My error message");

最佳答案

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");
}
}

在 Controller 中使用:
MyClass.errorMessage(ModelState);

在 View 中使用:
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
}
}
}

您可以从 this 获得更多帮助和 this链接。

关于asp.net-mvc - 使用 ASP.NET MVC,如何在外部 Controller 时显示错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43826280/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com