获取视图模型的模型状态键 属性

Get modelstate key for viewmodel property

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

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

代码

    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 对象,但我宁愿避免这种情况并想知道是否有更好的方法?

在 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.");