【发布时间】: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