使用ASP.NET MVC,如何在外部控制器上显示错误? [英] With ASP.NET MVC, how to display errors when outside controller?
本文介绍了使用ASP.NET MVC,如何在外部控制器上显示错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用:p在代码中的任何位置轻松地在视图中显示错误.
I'm trying to easily display errors in my View from anywhere in my code using :
@Html.ValidationSummary("", new { @class = "text-danger" })
在MVC之前,我使用过:
Before MVC, I used :
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
,但是我的问题是,当我不在Controller中时,我无法访问ModelState
.我尝试通过HttpContext
访问控制器或ModelState
,但没有找到一种方法.有什么主意吗?
Now with MVC, to add errors, I can't use currentPage.Validators
.
I need to use ModelState
but my problem is that I can't access ModelState
when I'm not in the Controller. I tried accessing the controller or the ModelState
via HttpContext
but I've not found a way to do it. Any idea ?
ModelState.AddModelError("", "My error message");
推荐答案
1.您可以通过ViewContext.ViewData.ModelState
访问它.然后使用
1. You can access it through ViewContext.ViewData.ModelState
. Then use
@if (!ViewContext.ViewData.ModelState.IsValid)
{
<div>There are some errors</div>
}
OR
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
3. ModelState
via ActionFilter
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.Controller.ViewData.ModelState.IsValid)
{
//Do Something
}
}
}
这篇关于使用ASP.NET MVC,如何在外部控制器上显示错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文