Published · 1 min read

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

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

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-invalid as 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 TagHelper instead 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-feedback in your inputs you have to do a single change, replace asp-for in the input tag with md-for.

<div class="md-form">
  <i class="fas fa-envelope prefix"></i>
  <input md-for="Input.Email" class="form-control" />
  <label asp-for="Input.Email">Your email</label>
  <span class="invalid-feedback" asp-validation-for="Input.Email"></span>
</div>

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

@addTagHelper Maxotek.WebAppUtils.Helpers.MdInputTagHelper, Maxotek.WebAppUtils
Partho Sarathi

Partho Sarathi

Founder, Maxotek

C# & .NET

Our blog

Related posts

Tutorials, notes and news from Maxotek.

  • C# Encode URL

    There are several ways you can encode URLs in C#. It all depends on what framework you are using.

    Partho Sarathi

    Partho Sarathi

  • C# Convert Int to Byte Array

    An Integer in C# is stored using 4 bytes with the values ranging from -2,147,483,648 to 2,147,483,647. Use the BitConverter.GetBytes() method to convert an integer to a byte array of size 4.

    Partho Sarathi

    Partho Sarathi

View all posts

See what Maxotek makes

Monitoring, conversion tools and more, built by the same people who wrote these posts.