Search code examples
asp.net-mvcmodelstate

ASP.NET MVC: how to add nested property to Modelstate?


I'd like to add a property to the Modelstate when it's not valid, but I'm not sure how to do that when the property is nested inside another.

Below is what Visual Studio already did for me.

<td>
    <span class="editor-field">
       @Html.EditorFor(model => model.TheResource.stateProvince)
    </span><span class="editor-validation-error">
       @Html.ValidationMessageFor(model => model.TheResource.stateProvince)
    </span>
 </td>

Now how do I add the property to modelstate on the server-side?

if(model.TheResource.countryName == "US")
{
    if(!GetUSAStates().Contains(stateProvince))
    {
       ModelState.AddModelError("", 
                                "US state or territory not valid." + 
                                "Please check the spelling. Use, for" + 
                                " instance, Maryland instead of MD");
    }
}

So far, I've been using empty string because I didn't know how to add the property. The problem is that it's displaying the error in the summary.

Any idea on how to add a nested property to Modelstate?

Thanks for helping


Solution

  • You can specify the fully qualified property name as the first parameter of .AddModelError

    ModelState.AddModelError("TheResource.stateProvince", ""US state or territory not valid ...");