【问题标题】:Get modelstate key for viewmodel property获取视图模型属性的模型状态键
【发布时间】:2015-06-04 12:43:10
【问题描述】:

我有一个添加产品表单,它取决于用户之前添加的类别、产品类型等。我不想让他们完成表单,然后意识到他们无法提交,而是希望在表单首次加载时显示错误。

我想针对适当的属性将此错误添加到模型状态 - 所以我的问题是如何获取该属性的模型状态键名称?

代码

    Model.Step1.PopulateData(_productTypeSvc.GetList(), _websiteSvc.GetMaximumNumberOfProductImages(HttpContext.Request.Url.Host));
    Model.Title = "Add A Product - Step 1: The Basics";
    if (Model.Step1.ProductTypes.IsNullOrEmpty())
    {
        //Rather than string.Empty, I want to programmatically get the correct key to add the error to..
        //E.g. if it were the view - HtmlHelper.NameFor(m => m.Step1.ProductTypeID)
        ModelState.AddModelError(string.Empty, "Please add at least one product type before adding products.");
    }

我知道我可以模拟 HtmlHelper 对象,但我宁愿避免这种情况并想知道是否有更好的方法?

【问题讨论】:

  • 它只是属性的完全限定名称 - ModelState.AddModelError("Step1.ProductTypeID", "Please ...");
  • 我知道,但我希望它是强类型的,而不是松散的字符串。
  • 它没有过载。您可以创建一个扩展方法并使用反射实现此表达式。

标签: c# asp.net-mvc modelstate


【解决方案1】:

在 MVC 中找到合适的扩展:

System.Web.Mvc.ExpressionHelper.GetExpressionText(LambdaExpression expression);

MSDN Here.

谢谢大家。

更新:

public static string GetPropertyName<TModel, TValue>(this TModel model, Expression<Func<TModel, TValue>> propertySelector)
{
     return ExpressionHelper.GetExpressionText(propertySelector);
}

然后使用扩展:

ModelState.AddModelError(Model.GetPropertyName(m => m.Step1.ProductTypeID), "Please add at least one product type before adding products.");

【讨论】:

  • 好的,但是在这种情况下你是如何使用ExpressionHelper.GetExpressionText的呢?
  • @ctekse,我已经更新了我在实现中给出的答案——即利用内置的表达式助手在 System.Web.Mvc 命名空间中创建一个扩展。希望这会有所帮助。
  • 类似SO post,这是AddModelError的扩展。顺便说一句,不是我的帖子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-11
  • 2013-10-20
  • 1970-01-01
  • 1970-01-01
  • 2018-06-15
  • 1970-01-01
  • 2012-07-11
相关资源
最近更新 更多