How do you get errors in ModelState for a specific property?

I ran into the following problem: https://github.com/aspnet/Mvc/issues/4989 , and based on the 'rsheptolut' comment of September 12, 2016, he found this workaround (inserted for convenience):

<form class="form-horizontal" asp-antiforgery="true">
  <fieldset>
    // All of this instead of @Html.ValidationSummary(false) due to a bug in ASP.NET Core 1.0
    @if (!@ViewData.ModelState.IsValid)
    {
        var errors = ViewData.ModelState.Values.Select(item => item.Errors.FirstOrDefault()?.ErrorMessage).Where(item => item != null);
        <div class="alert alert-danger">
            <span>@Localizer["There are problems with your input:"]</span>
            <ul>
                @foreach (var error in errors)
                {
                    <li>@error</li>
                }
            </ul>
        </div>
    }

    // Some actual fields. Don't forget validation messages for fields if you need them (@Html.ValidationMessage)
  </fieldset>
</form>

My problem is with LINQ to get the variable errors. I want to filter them by property name, so the list of errors listed in the file upload element will not contain errors of other elements on the page. I want to do something like this:

ViewData.ModelState.Values.Where(item => item.Key == "Images").Select...;

However, LINQ does not find Key as a valid property of the ModelStateEntry class. Fair. But why then, adding a quick scan to ViewData.ModelState.Values, does the Key property appear?

+4
1

, (-) proeprty Name

string propertyName = "Name";

( @Html.ValidationSummary(),

string error = ViewData.ModelState.Keys.Where(k => k == propertyName)
    .Select(k => ModelState[k].Errors[0].ErrorMessage).First();

IEnumerable<string> errors = ModelState.Keys.Where(k => k == propertyName)
    .Select(k => ModelState[k].Errors).First().Select(e => e.ErrorMessage);

foreach,

+4

Source: https://habr.com/ru/post/1667803/


All Articles