如何获取列表中项的ModelState键

问题

我有一个用户可以编辑的字段列表。 提交模型时,我想检查这些项是否有效。 我不能使用数据符号,因为每个字段都有不同的validation过程,直到运行时才会知道。 如果validation失败,我使用ModelState.AddModelError(string key, string error) ,其中键是要添加错误消息的html元素的名称。 由于有一个字段列表,Razor为html项生成的名称就像Fields[0].DisplayName 。 我的问题是有一种方法或方法从视图模型中获取生成的html名称的密钥吗?

试图解决方案

我没有运气,为密钥尝试了toString()方法。 我也查看了HtmlHelper类,但我没有看到任何有用的方法。

代码片段

查看模型

 public class CreateFieldsModel { public TemplateCreateFieldsModel() { FreeFields = new List(); } [HiddenInput(DisplayValue=false)] public int ID { get; set; } public IList FreeFields { get; set; } public class TemplateFieldModel { [Display(Name="Dispay Name")] public string DisplayName { get; set; } [Required] [Display(Name="Field")] public int FieldTypeID { get; set; } } } 

调节器

 public ActionResult CreateFields(CreateFieldsModel model) { if (!ModelState.IsValid) { //Where do I get the key from the view model? ModelState.AddModelError(model.FreeFields[0], "Test Error"); return View(model); } } 

在挖掘源代码后,我找到了解决方案。 有一个名为ExpressionHelper的类,用于在EditorFor()时为字段生成html名称。 ExpressionHelper类有一个名为GetExpressionText()的方法,它返回一个字符串,该字符串是该html元素的名称。 这是如何使用它…

 for (int i = 0; i < model.FreeFields.Count(); i++) { //Generate the expression for the item Expression> 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); } 

您必须根据渲染表单中字段的方式构建控制器内部的键(输入元素的名称)。

对于前者 如果对CreateFieldsModelFreeFields集合中的第二项的validation失败,则可以将输入元素的名称框架化,即密钥为FreeFields[1].DisplayName ,其中将映射validation错误。

据我所知,你不能轻易从控制器那里得到它。