在我的 .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提供了一个优秀的解决方案!