我的 .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/