简体   繁体   中英

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

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")

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM