[英]How to get a ModelState key of an item in a list
问题
我有一个用户可以编辑的字段列表。 提交模型时,我想检查这些项是否有效。 我不能使用数据表示法,因为每个字段都有不同的验证过程,直到运行时才会知道。 如果验证失败,我使用ModelState.AddModelError(string key, string error)
,其中键是要添加错误消息的html元素的名称。 由于有一个字段列表,Razor为html项生成的名称就像Fields[0].DisplayName
。 我的问题是有一种方法或方法从视图模型中获取生成的html名称的密钥?
试图解决方案
我没有运气,为密钥尝试了toString()
方法。 我也查看了HtmlHelper
类,但我没有看到任何有用的方法。
代码片段
查看模型
public class CreateFieldsModel
{
public TemplateCreateFieldsModel()
{
FreeFields = new List<FieldModel>();
}
[HiddenInput(DisplayValue=false)]
public int ID { get; set; }
public IList<TemplateFieldModel> 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<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);
}
您必须根据渲染表单中字段的方式构建控制器内部的键(输入元素的名称)。
对于前者 如果对CreateFieldsModel
的FreeFields
集合中的第二项的验证失败,则可以将输入元素的名称框架化,即键为FreeFields[1].DisplayName
,其中将映射验证错误。
据我所知,你不能轻易从控制器那里得到它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.