我的 .Net 5./ASP.Net MVC 应用程序中有一个“编辑”页面。如果
ModelState.IsValid
为“false”,我想在拒绝整个页面之前检查各个错误。
问题:如何获取
ModelState
列表中无效项目的“名称”?
例如:
处理方法:
public async Task<IActionResult> OnPostAsync()
if (!ModelState.IsValid)
:“假”
this.ModelState.Values[0]:SubKey={ID},Key="ID",ValidationState=无效 Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateEntry {Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary.ModelStateNode}
代码:
foreach (ModelStateEntry item in ModelState.Values)
{
if (item.ValidationState == ModelValidationState.Invalid)
{
// I want to take some action if the invalid entry contains the string "ID"
var name = item.Key; // CS1061: 'ModelStateEntry 'does not contain a definition for 'Key'
...
问题:如何从每个无效的 ModelState“值”项中读取“键”???
解决方案
我的基本问题是迭代“ModelState.Values”。相反,我需要迭代“ModelState.Keys”才能获取所有必需的信息。
解决方案1)
foreach (KeyValuePair<string, ModelStateEntry> modelStateDD in ModelState)
{
string key = modelStateDD.Key;
ModelStateEntry item = ModelState[key];
if (item.ValidationState == ModelValidationState.Invalid) {
// Take some action, depending on the key
if (key.Contains("ID"))
...
解决方案2)
var errors = ModelState
.Where(x => x.Value.Errors.Count > 0)
.Select(x => new { x.Key, x.Value.Errors })
.ToList();
foreach (var error in errors) {
if (error.Key.Contains("ID"))
continue;
else if (error.Key.Contains("Foo"))
...
非常感谢 devlin carnate 为我指明了正确的方向,并感谢 PippoZucca 提供了一个很好的解决方案!
调试时,您可以输入以下内容:
ModelState.Where(
x => x.Value.Errors.Count > 0
).Select(
x => new { x.Key, x.Value.Errors }
)
进入您的手表窗口。 这将收集所有生成错误的密钥以及错误描述。
此 linq 查询会生成一个列表,其中所有错误消息都连接到其键。
var result2 = ModelState.SelectMany(m => m.Value.Errors.Select(s => new { m.Key, s.ErrorMessage }));
问候西尔弗罗