pau*_*sm4 6 c# modelstate asp.net-core-mvc .net-5
我的 .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'
...
Run Code Online (Sandbox Code Playgroud)
问题:如何从每个无效的 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"))
...
Run Code Online (Sandbox Code Playgroud)
解决方案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"))
...
Run Code Online (Sandbox Code Playgroud)
非常感谢 devlin carnate 为我指明了正确的方向,并感谢 PippoZucca 提供了一个很好的解决方案!
小智 7
调试时,您可以输入以下内容:
ModelState.Where(
x => x.Value.Errors.Count > 0
).Select(
x => new { x.Key, x.Value.Errors }
)
Run Code Online (Sandbox Code Playgroud)
进入您的手表窗口。这将收集所有生成错误的密钥以及错误描述。
| 归档时间: |
|
| 查看次数: |
3230 次 |
| 最近记录: |