-1

I have a RazorPage application and in the _layout.cshtml file i have the following code snippet:

@if (ViewData.ModelState[""].Errors.Count > 0)
{
    <div class="alert alert-error">
       <button type="button" class="close" data-dismiss="alert">×</button>
       @Html.ValidationSummary(true, "Errors: ")
    </div>
}

Browsing in the Microsoft source code it would seem that the Errors property should never be null, but instead, it is not, in fact sometimes this property is null and therefore without conditional access with the ? on Errors like this:

@if (ViewData.ModelState[""].Errors?.Count > 0)

in some cases, it can cause a NullReferenceException. Is there any bug in my code? the Errors property has only get not set:

enter image description here

so even if I wanted I could not set it to null.Why does this happen? I just can't explain this to myself. Thanks

UPDATE

Digging and debugging this code again, I realized that the ModelStateEntry with the key "" is null

 (ViewData.ModelState[""]) is null

if the error is raised by the IdentityServer middleware and not by my pages, where I just used an empty string as the key. In fact, from the Asp.Net Core source code we have:

public ModelStateEntry this[string key]
{
    get
    {
        if (key == null)
        {
            throw new ArgumentNullException(nameof(key));
        }

        TryGetValue(key, out var entry);
        return entry!;
    }
}

public bool TryGetValue(string key, [NotNullWhen(true)] out ModelStateEntry? value)
{
    if (key == null)
    {
        throw new ArgumentNullException(nameof(key));
    }

    var result = GetNode(key);
    if (result?.IsContainerNode == false)
    {
        value = result;
        return true;
    }

    value = null; // Retunr null if key not found
    return false;
}

In this case, I would have expected plus a KeyNotFoundException.

Thanks for the help anyway.

Solution

In the end, since in the case of errors from the pages I want to show those types of errors in the relative popup, while in the other cases I just want to show the error messages of IdentityServer rendered in a different page and that uses an IS4 ErrorMessage object, I simply inserted the two conditional accesses as follows:

enter image description here

The only "problem" is that the ide Rider continues to indicate them as removable. I will open a bug on the related site.

Thanks

Update for those who voted negatively on my question

enter image description here

https://youtrack.jetbrains.com/issue/RSRP-486576

pampua84
  • 696
  • 10
  • 33

1 Answers1

2

If you want to get the number of all errors,try to use:

ViewData.ModelState.Where(n => n.Value.Errors.Count > 0).ToList().Count()

If you want to get all the errors for a property,try to use:

ModelState.Keys.Where(k => k == "Name")
     .Select(k => ModelState[k].Errors).First().Select(e => e.ErrorMessage)
Yiyi You
  • 16,875
  • 1
  • 10
  • 22