Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get errors in the ModelState, for a particular property?

Tags:

I'm encountering the following issue: https://github.com/aspnet/Mvc/issues/4989, and based on 'rsheptolut' comment on Sep 12, 2016, he found this workaround (pasted 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 ([email protected])
    {
        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 issue is with the LINQ to get the errors variable. I want to filter these by the name of the property, so the list of errors listed under my file uploads element will not contain errors from other elements on the page. I want to do something like this:

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

However, LINQ doesn't find Key as a valid property of the ModelStateEntry class. Fair enough. But why then, when add a quick watch to ViewData.ModelState.Values, does the Key property show up?