How to create a reusable solution for asp.net mvc ValidationMessageFor

140 Views Asked by At

I currently got following snippet:

@Html.EditorFor(model => model.Street, new { htmlAttributes = new { @class = "form-control tooltp", placeholder = "Rue *", autofocus = "autofocus", data_tooltip_content = "#Street_content" } })
@if (ViewData.ModelState["Street"] != null && ViewData.ModelState["Street"].Errors.Any())
{
    <div class="tooltip_templates">
        <div id="street_content">
            @Html.ValidationMessageFor(model => model.Street)
        </div>
    </div>
}

How can I make this reusable? Create an MVC helper? Partial view? It's not possible?

I would like to have this kind of solution so that I can use it for all my different fields. I'm using tooltipster for the tooltip messages. Without the if statement, the tooltip will contain an empty string (but will still be shown).

I'd like to have a solution where I can for example do this

@ErrorHelper.ShowError("Street")
1

There are 1 best solutions below

3
On BEST ANSWER

I have my own validation message helper to auto add the bootstrap class styles

public static MvcHtmlString MyValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string tag)
{
    return htmlHelper.ValidationMessage(tag, new { @class = "text-danger" });
}
public static MvcHtmlString MyValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
    return htmlHelper.ValidationMessageFor(expression, "", new { @class = "text-danger" });
}

and used like @Html.MyValidationMessageFor(x => x.Street)

You could easily adapt this to check if the meta data was null or not and return nothing if it is.