如何获取列表中项的ModelState键

Ste*_*aly 19 c# model-view-controller asp.net-mvc modelstate

问题

我有一个用户可以编辑的字段列表.提交模型时,我想检查这些项是否有效.我不能使用数据表示法,因为每个字段都有不同的验证过程,直到运行时才会知道.如果验证失败,我使用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; }
    }
}
Run Code Online (Sandbox Code Playgroud)

调节器

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

Ste*_*aly 28

在挖掘源代码后,我找到了解决方案.有一个被调用的类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);
}
Run Code Online (Sandbox Code Playgroud)

  • 这很好,但刚刚找到另一个帖子,用一个很好的扩展方法包装这个逻辑:http://stackoverflow.com/a/12689563/1825109 (4认同)