如何在 ASP.NET MVC 中获取模型状态错误的集合? [英] How do I get the collection of Model State Errors in ASP.NET MVC?
问题描述
如何获取视图中的错误集合?
How do I get the collection of errors in a view?
我不想使用 Html Helper 验证摘要或验证消息.相反,我想检查错误以及是否以特定格式显示它们.同样在输入控件上,我想检查特定的属性错误并向输入添加一个类.
I don't want to use the Html Helper Validation Summary or Validation Message. Instead I want to check for errors and if any display them in specific format. Also on the input controls I want to check for a specific property error and add a class to the input.
附言我正在使用 Spark 视图引擎,但想法应该是一样的.
P.S. I'm using the Spark View Engine but the idea should be the same.
所以我想我可以做一些像......
So I figured I could do something like...
<if condition="${ModelState.Errors.Count > 0}">
DisplayErrorSummary()
</if>
....and also...
<input type="text" value="${Model.Name}"
class="?{ModelState.Errors["Name"] != string.empty} error" />
....
或者类似的东西.
更新
我的最终解决方案如下:
My final solution looked like this:
<input type="text" value="${ViewData.Model.Name}"
class="text error?{!ViewData.ModelState.IsValid &&
ViewData.ModelState["Name"].Errors.Count() > 0}"
id="Name" name="Name" />
如果这个属性有错误,这只会添加错误 css 类.
This only adds the error css class if this property has an error.
推荐答案
<% ViewData.ModelState.IsValid %>
或
<% ViewData.ModelState.Values.Any(x => x.Errors.Count >= 1) %>
对于特定的属性...
<% ViewData.ModelState["Property"].Errors %> // Note this returns a collection
这篇关于如何在 ASP.NET MVC 中获取模型状态错误的集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!