0

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")
Senne
  • 183
  • 1
  • 10

1 Answers1

1

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.

Eonasdan
  • 7,563
  • 8
  • 55
  • 82
  • Hi, thanks for your comment. Any idea about the meta data? I have access to htmlHelper.ViewData.ModelState, but I should only know it for this specific property, not the whole model. – Senne Aug 23 '16 at 11:48
  • Nevermind, I can access the name with this: var propertyName = ExpressionHelper.GetExpressionText(expression); – Senne Aug 23 '16 at 12:03
  • don't forget to up vote and accept if this helped you – Eonasdan Aug 23 '16 at 16:09