Change the error class of asp-for in .NET Core’s MVC

Partho Sarathi

25 Feb, 2019 · 2 minutes read

  • Share:

This is a problem I ran into when converting my Bootstrap 3 based site to MDB which is based on Bootstrap 4.

The validation class in MDB is is-invalidas opposed to input-validation-error. I think it’s because of Bootstrap as opposed to MDB itself. But, in any case I had to change it with minimal code.

One solution is given here.

Adding the @Html.FieldHasError(m => m.Password)in the class attribute of every input seems to be too much work. So, here is my solution that uses TagHelperinstead of extension methods on IHtmlHelper.

  [HtmlTargetElement("input", Attributes = "md-for", TagStructure = TagStructure.WithoutEndTag)]
public class MdInputTagHelper : InputTagHelper
{
    public MdInputTagHelper(IHtmlGenerator generator)
        : base(generator)
    {
    }

    [HtmlAttributeName("md-for")]
    public ModelExpression MdFor 
    {
        get => For;
        set => For = value;
    } 

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        base.Process(context, output);

        var fullName = NameAndIdProvider.GetFullHtmlFieldName(ViewContext, For.Name);

        if (ViewContext.ViewData.ModelState.TryGetValue(fullName, out var entry) && entry.Errors.Count > 0)
        {
            output.AddClass("is-invalid", HtmlEncoder.Default);
            output.RemoveClass("input-validation-error", HtmlEncoder.Default);
        }
    }
}

Now, to use the class invalid-feedbackin your inputs you have to do a single change, replace asp-forin the input tag with md-for.

  
    

One last thing, remember to import the tag helper in your _ViewImports.cshtmlfile:-

  @addTagHelper Maxotek.WebAppUtils.Helpers.MdInputTagHelper, Maxotek.WebAppUtils
  • Share:

The cleanest blogging platform


2024 © Maxotek. All rights reserved.