从我的自定义帮助器中访问ModelState?

时间:2014-02-20 09:24:44

标签: asp.net-mvc asp.net-mvc-5

我只是想做一个这样的助手:

    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?

1 个答案:

答案 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
        }
    }