c# - ASP.Net 核心 : How do you get the key of an invalid ModelState value?

标签 c# asp.net-core-mvc .net-5 modelstate

我的 .Net 5./ASP.Net MVC 应用程序中有一个“编辑”页面。如 ModelState.IsValid是“假”,我想在拒绝整个页面之前检查个别错误。
问题 :如何在 ModelState 中获取无效项目的“名称”列表?
例如:

  • 处理程序方法:public async Task<IActionResult> OnPostAsync()
  • if (!ModelState.IsValid) : “错误的”
    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 提供了一个很好的解决方案!

    最佳答案

    在调试时,您可以键入:

    ModelState.Where(
      x => x.Value.Errors.Count > 0
    ).Select(
      x => new { x.Key, x.Value.Errors }
    )
    
    进入您的观察窗口。
    这将收集所有产生错误的 key 以及错误描述。

    关于c# - ASP.Net 核心 : How do you get the key of an invalid ModelState value?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69168542/

    相关文章:

    c# - 在 Windows Phone 8.1 中共享渲染到位图图像

    asp.net-mvc - 结合 asp-route-id 和 asp-route-all-data

    binaryformatter - 有没有一种高性能的方法来替换 .NET5 中的 BinaryFormatter?

    c# - 无论如何在 linq to entities 查询中生成自定义 sql?

    c# - 如何将我们在控制台窗口上的操作保存到文本文件中?

    asp.net-core - 带有 Postgres 连接字符串错误的 EF Core

    c# - 在 ASP.NET 5 中找不到 CSS 文件

    azure - 将面向新版本 .NET 的 ASP.NET Core 应用部署到现有的 Azure 应用服务?

    entity-framework-core - 在指定场景下是否值得将 Dotnet Standard 2.1 迁移到 .Net 6

    javascript - Bot框架直线502错误