ASP.Net Core:如何获取无效的ModelState值的键?

6

在我的 .Net 5./ASP.Net MVC 应用程序中,我有一个“编辑”页面。如果 ModelState.IsValid 的值为“false”,我想在拒绝整个页面之前检查单个错误。

问题:如何获取 ModelState 列表中无效项的“名称”?

例如:

  • 处理程序方法: public async Task<IActionResult> OnPostAsync()

  • if (!ModelState.IsValid): "false"

    this.ModelState.Values[0]: SubKey={ID}, Key="ID", ValidationState=Invalid 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 "Values"项中读取"Key"?


解决方法

我的基本问题是遍历"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提供了一个优秀的解决方案!

这个线程中选择的答案是否回答了你的问题?(还要看一下那个被选中答案的评论,因为有人解释了如何获取“key”) - devlin carnate
@devlin carnate: 谢谢你的回复。我查看了那个链接中提供的解决方案。不幸的是,它们只检索错误消息。 我想知道导致错误的模型对象的名称。这是我还没能弄清楚的部分。 - FoggyDay
这个回答解决了你的问题吗?如何从ASP.Net MVC ModelState获取所有错误? - Serge
@FoggyDay:所以你尝试了评论中的解决方案吗?评论是由“viggity”发布的。它明确说明它按键显示错误… - devlin carnate
2个回答

6

在调试时,您可以输入以下内容:

ModelState.Where(
  x => x.Value.Errors.Count > 0
).Select(
  x => new { x.Key, x.Value.Errors }
)

将所有生成错误的键以及其错误说明收集到您的监视窗口中。

太棒了 - 正是我想要的。它将“关键字”和“错误”结合在一起,以便我可以按字段名称检查每个模型错误。完美 - 谢谢! - FoggyDay

0
这个 Linq 查询会返回一个列表,其中包含与其键相关联的所有错误消息。
var result2 = ModelState.SelectMany(m => m.Value.Errors.Select(s => new { m.Key, s.ErrorMessage }));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接