Black
Black

Reputation: 5377

AspNetCore ModelState type missing in one specific context

I have a Controller action in my Asp Net Core (2.2) project. I have declared

    using Microsoft.AspNetCore.Mvc.ModelBinding;

Action code is as follows:

    1:   public IActionResult Index()
    2:   {
    3:       var errors = ModelState.Values.SelectMany(v => v.Errors);
    4:       foreach ( ModelState modelState in ViewData.ModelState.Values)
    ...

For some reason, the compiler is highlighting line 4 with a message

Error CS0246 The type or namespace name 'ModelState' could not be found (are you missing a using directive or an assembly reference?) ics-billing C:\Users...\Controllers\HomeController.cs 30 Active

I don't understand how the compiler is unable to resolve the type 'ModelState' on line 4, whereas it has no problem with exactly the same class being referenced on line 3?

Upvotes: 1

Views: 1612

Answers (2)

Mohamed Elamin
Mohamed Elamin

Reputation: 375

You can loop for ModelState errors by this code:

            if (!ModelState.IsValid)
            {
                ViewBag.Message = string.Join("; ", ModelState.Values
                                    .SelectMany(x => x.Errors)
                                    .Select(x => x.ErrorMessage));                    
                return View(model);
            }

Upvotes: 1

Matt U
Matt U

Reputation: 5118

ModelState on line three is a property of the ControllerBase class, which is what Controller inherits from. On line four, it's looking for a type named ModelState but that type doesn't exist. The ModelState property is of type ModelStateDictionary: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.controllerbase.modelstate?view=aspnetcore-3.0#Microsoft_AspNetCore_Mvc_ControllerBase_ModelState

And the Values property of ModelStateDictionary is of type ValueEnumerable: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.modelbinding.modelstatedictionary.values?view=aspnetcore-3.0#Microsoft_AspNetCore_Mvc_ModelBinding_ModelStateDictionary_Values

Which is an IEnumerable of ModelStateEntry: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.modelbinding.modelstatedictionary.valueenumerable?view=aspnetcore-3.0

I believe you need to change ModelState modelState on line four to ModelStateEntry modelStateEntry. However, you can also use var instead of specifying the type name.

Upvotes: 3

Related Questions