How to get a ModelState key of an item in a list

帅比萌擦擦* 提交于 2019-12-03 04:54:30

After digging around in the source code I have found the solution. There is a class called ExpressionHelper that is used to generate the html name for the field when EditorFor() is called. The ExpressionHelper class has a method called GetExpressionText() that returns a string that is the name of that html element. Here is how to use it ...

for (int i = 0; i < model.FreeFields.Count(); i++)
{
    //Generate the expression for the item
    Expression<Func<CreateFieldsModel, string>> expression = x => x.FreeFields[i].Value;
    //Get the name of our html input item
    string key = ExpressionHelper.GetExpressionText(expression);
    //Add an error message to that item
    ModelState.AddModelError(key, "Error!");
}

if (!ModelState.IsValid)
{
    return View(model);
}

You have to frame the key(name of the input element) inside the controller based upon how you are rendering the fields in the form.

For ex. if the validation of the second item in the FreeFields collection of CreateFieldsModel fails you can frame the name of the input element i.e. key as FreeFields[1].DisplayName where the validation error is going to be mapped.

As far as I know you can't easily get that from controller.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!