Access ModelState from my user assistant?

I just want to make such an Assistant:

    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());
    }

So the question is how to access the actual ModelState here?

+3
source share
1 answer

You can use the following code:

    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
        }
    }
+4
source

All Articles