我只是想做一个这样的助手:
public static MvcHtmlString HasError<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
StringBuilder sb = new StringBuilder();
if (!ModelState.IsValidField(ExpressionHelper.GetExpressionText(expression)))
sb.Append("has-error");
return MvcHtmlString.Create(sb.ToString());
}
所以问题 - 如何在这里访问实际的ModelState?
答案 0 :(得分:4)
您可以使用以下代码:
foreach (var state in htmlHelper.ViewData.ModelState)
{
// Do what you what with the ModelState here
foreach (var error in state.Value.Errors)
{
// Display error here
}
}