custom ValidationForMessage helper removing css element

后端 未结 1 1473
伪装坚强ぢ
伪装坚强ぢ 2020-12-22 11:15

Hi have an html helper that allows me to apply a different style to the ValidationForMessage.

My question is how to I tap into the validation event to either change

1条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-22 11:40

    Here's how you could proceed:

    public static MvcHtmlString ValidationStyledMessageFor(this HtmlHelper htmlHelper, Expression> ex)
    {
        var expression = ExpressionHelper.GetExpressionText(ex);
        var modelName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expression);
        var modelState = htmlHelper.ViewData.ModelState[modelName];
        var modelErrors = modelState == null ? null : modelState.Errors;
        var modelError = ((modelErrors == null) || (modelErrors.Count == 0)) 
            ? null 
            : modelErrors.FirstOrDefault(m => !String.IsNullOrEmpty(m.ErrorMessage)) ?? modelErrors[0];
        var result = htmlHelper.ValidationMessageFor(ex);
    
        if (modelError != null)
        {
            // There was an error => remove the hidden class
            return MvcHtmlString.Create(string.Format(" 

    {0}

    ", result.ToHtmlString())); } return MvcHtmlString.Create(string.Format("

    {0}

    ", result.ToHtmlString())); }

    UPDATE:

    If you have client side validation enabled you will also need to plug into the jquery validate plugin and manually indicate how to highlight/unhighlight error fields as you have customized the markup. This can be done by simply overriding the default values of the plugin:

    
    

    0 讨论(0)
提交回复
热议问题