ModelState.AddModelError - 如何添加不属于属性的错误? [英] ModelState.AddModelError - How can I add an error that isn't for a property?

查看:46
本文介绍了ModelState.AddModelError - 如何添加不属于属性的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Create(FooViewModel fvm){...} 中检查我的数据库以查看fvm.prop1fvm.prop2> 已经存在于该组合中;如果是这样,我想向模型状态添加一个错误,然后返回整个视图.我试过了:

I am checking my database in Create(FooViewModel fvm){...} to see if the fvm.prop1 and fvm.prop2 already exist in that combination; if so, I want to add an error to the modelstate, then return the whole view. I tried:

public ActionResult Create(FooViewModel fvm){
    if (ThatComboAlreadyExists(fvm)) {
      ModelState.AddModelError("Model", "There is already one like that");
      return View(fvm);
    }
}

...但我没有在 Html.ValidationSummary 中显示错误,我认为它们会出现在这里.我怀疑模型"不是正确的键,但我在谷歌上找不到任何东西.

...but I get no display of errors in the Html.ValidationSummary, which is where I assume they would appear. I have the suspicion that "Model" is not the right key, but I haven't been able to find anything a la Google.

推荐答案

我最终偶然发现了 一个我正在寻找的用法的示例 - 通常将错误分配给模型,而不是其中之一它的属性,像往常一样调用:

I eventually stumbled upon an example of the usage I was looking for - to assign an error to the Model in general, rather than one of it's properties, as usual you call:

ModelState.AddModelError(string key, string errorMessage);

但使用空字符串作为键:

but use an empty string for the key:

ModelState.AddModelError(string.Empty, "There is something wrong with Foo.");

错误消息将如您所料出现在 <%: Html.ValidationSummary() %> 中.

The error message will present itself in the <%: Html.ValidationSummary() %> as you'd expect.

这篇关于ModelState.AddModelError - 如何添加不属于属性的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆