我有一个视图,它由2个局部视图加上页面中已有的视图组成。我希望每个视图都有一个验证摘要。一切都运行正常,但是当其中一个部分出现错误时,消息会显示在每个验证摘要中,因此页面中有3次。我想解决这个问题。
我在网上看了一下,看到有办法这样做:
var SecurityQuestionsErrors = ViewData.ModelState.Where(ms => ms.Key == "SecurityQuestions");
if (SecurityQuestionsErrors.Count()>0)
{
@Html.ValidationSummary("", new { @class = "" })
}
所以我会在每个局部视图中都有这个代码,以查看错误是否特别适用于此。
当错误来自控制器时(我可以自己添加一个键,它可以正常工作):
catch (FaultException<IncorrectQuestionFault>)
{
// question is incorect
ModelState.AddModelError("SecurityQuestions", Resources.errors.incorrectQuestion);
}
但是当错误来自ViewModel时,它并没有添加密钥而且搞砸了......
[Required(ErrorMessageResourceName = "IsRequired", ErrorMessageResourceType = typeof(Resources.errors))]
[StringLength(40, MinimumLength = 7, ErrorMessageResourceName = "NotLongEnough", ErrorMessageResourceType = typeof(Resources.errors))]
[Display(Order = 0, Name = "question", ResourceType = typeof(Resources.errors))]
public string question{ get; set; }
所以我的问题是:我这样做的好方法吗?有没有办法为来自ViewModel的错误添加密钥?我应该用另一种方式吗?
感谢所有帮助:D
答案 0 :(得分:0)
假设这是您的View模型属性:
[Required(ErrorMessageResourceName = "IsRequired", ErrorMessageResourceType = typeof(Resources.errors))]
[StringLength(40, MinimumLength = 7, ErrorMessageResourceName = "NotLongEnough", ErrorMessageResourceType = typeof(Resources.errors))]
[Display(Order = 0, Name = "question", ResourceType = typeof(Resources.errors))]
public string question{ get; set; }
@Html.ValidationSummary(false, "", new { @class = "text-danger" })
@Html.LabelFor(x => x.question)
@Html.EditorFor(x => x.question)
默认情况下会将所有验证错误都放在他们自己的div中
如果您试图捕获控制器上的错误,您可以:
if (!ModelState.IsValid)
{
// the model is invalid
//if you are trying to catch different errors here
var modelStateErrors = this.ModelState.Values.SelectMany(m => m.Errors);
//Now you have all the errors and can give specific messages for a given error
ModelState.AddModelError(string.Empty, "Your error goes here");
}