ModelState.AddModelError - 我如何添加一个错误,不是财产? [英] ModelState.AddModelError - How can I add an error that isn't for a property?
问题描述
我检查我的数据库中创建(FooViewModel FVM){...}
来查看是否 fvm.prop1
和 fvm.prop2
已经存在在组合;如果是的话,我想的错误添加到的ModelState,则返回全图。我想:
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);
}
}
...但我没有得到任何的验证摘要,这是错误的显示,我相信他们会出现。我有怀疑,模式是不正确的钥匙,但我一直没能找到任何一拉谷歌。
...but I get no display of errors in the validation summary, 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.
推荐答案
我最终偶然发现的an我一直在寻找的使用的例子 - 的错误分配给一般的模型,而不是它的一个特性,像往常一样打电话:
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.");
该错误消息将present自己在<%:Html.ValidationSummary()%GT;
如你所期望
这篇关于ModelState.AddModelError - 我如何添加一个错误,不是财产?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!