ASP.NET MVC:如何将嵌套属性添加到Modelstate?

Ric*_*d77 3 asp.net-mvc modelstate

我想在Modelstate无效时向Modelstate添加一个属性,但是我不确定当属性嵌套在另一个属性中时该怎么做.

以下是Visual Studio已经为我做的事情.

<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>
Run Code Online (Sandbox Code Playgroud)

现在如何在服务器端将属性添加到modelstate?

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,我一直在使用空字符串,因为我不知道如何添加属性.问题是它在摘要中显示错误.

有关如何将嵌套属性添加到Modelstate的任何想法?

谢谢你的帮助

小智 6

您可以将完全限定的属性名称指定为第一个参数 .AddModelError

ModelState.AddModelError("TheResource.stateProvince", ""US state or territory not valid ...");
Run Code Online (Sandbox Code Playgroud)