How to extend Html.ValidationMessage to include image as error?

I would like to reduce the following code. The code below works, however it is not very neat, etc.

    <label for="Name">Name:</label><%= Html.TextBox("Name")%><% 
    if (!string.IsNullOrEmpty(Html.ValidationMessage("Name"))) {
        string Error = HtmlRemoval.StripTags(Html.ValidationMessage("Name")); %>
        <img src="Error.gif" alt="Error" title="<%= Error %>" /><%
    }
    %>

I read that I need to extend the Html helper so that I can return an image instead of text containing a default element and a text error.

I cannot find articles or general tips on how I accomplished this. I am still very new to ASP.NET MVC. Any advice would be greatly appreciated.

+3
source share
7 answers

You can extend the HtmlHelper as:

public static class CustomHtmlHelper {

  public static string ValidationImage(this HtmlHelper helper, string name) {
    if (helper.ViewData.ModelState[name] == null || helper.ViewData.ModelState[name].Errors == null) {
      return String.Empty;
    }
    TagBuilder tag = new TagBuilder("img");
    tag.Attributes.Add("src", "Error.gif");
    tag.Attributes.Add("alt", "Error");
    tag.Attributes.Add("title", helper.ViewData.ModelState[name].Errors[0].ErrorMessage);
    return tag.ToString(TagRenderMode.SelfClosing);
  }

}

Then on your page, import the class containing the extension method

<%@ Import Namespace="CustomHtmlHelperNamespace" %>

Then add the following to your page:

<label for="Name">Name:</label>
<%= Html.TextBox("Name")%>
<% Html.ValidationImage("Name") %>

HtmlHelper , HtmlHelper, ViewState , ( "" ), , HTML-, . title ""

+13

Html Helper, , , . 100% , , :

public class HtmlHelperExtensions {

    public static string GetMeSomething(this HtmlHelper helper)
    {
        //... Do things here. ...
    }
}

- , Html.GetMeSomething, .

+1

ValidationMessage ... ,

<span class="field-validation-error">You must specify a username.</span>

, , CSS / jQuery , .

, CSS , DIV, - :

.field-validation-error
{
    background: url(x.gif) no-repeat;
    padding-left:10px;
    color: #ff0000;
}

<div style="width:10px; height:10px; overflow:hidden;">
    <%= Html.ValidationMessage("username") %>
</div>

10x10 gif , / "". . ValidationMessage MVC , , , , , Javascript, .

: Message Validation, MVC. ( ), . - - , .

public static string MyValidationMessage(this HtmlHelper htmlHelper, string modelName, string validationMessage)
{
    if (modelName == null)
        throw new ArgumentNullException("modelName");

    if (!htmlHelper.ViewData.ModelState.ContainsKey(modelName))
        return null;

    ModelState modelState = htmlHelper.ViewData.ModelState[modelName];
    ModelErrorCollection modelErrors = (modelState == null) ? null : modelState.Errors;
    ModelError modelError = ((modelErrors == null) || (modelErrors.Count == 0)) ? null : modelErrors[0];

    if (modelError == null) 
        return null;

    return "<img src=\"../../Content/x.gif\" alt=\"Error\" title=\"" + validationMessage + "\" />";
}
+1

. , Html Mvc.

David ( MVC3 w/Razor):

  • ; , , (UI) MvcHtmlString.Create(). MvcHtmlString. Helper .

  • , RegEx .., , "If..Then.." ; , "Null" . Errors null, .

, CustomHtmlHelper , css:

#Region "Imports"

Imports System.Runtime.CompilerServices

#End Region

Namespace Laddawn.Web.Mvc.Extensions

    Public Module CustomHtmlHelpers

        <Extension()>
        Public Function ValidationImage(ByVal helper As HtmlHelper, ByVal name As String) As MvcHtmlString

            If helper.ViewData.ModelState(name) Is Nothing _
            OrElse helper.ViewData.ModelState(name).Errors Is Nothing _
            OrElse helper.ViewData.ModelState(name).Errors.Count = 0 Then
                Return MvcHtmlString.Empty
            End If

            Dim tag As New TagBuilder("img")

            With tag
                .Attributes.Add("src", "/Content/Images/Mobile/alert.png")
                .Attributes.Add("alt", helper.ViewData.ModelState(name).Errors(0).ErrorMessage)
                .Attributes.Add("title", helper.ViewData.ModelState(name).Errors(0).ErrorMessage)
                .Attributes.Add("class", HtmlHelper.ValidationMessageCssClassName)
            End With

            Return MvcHtmlString.Create(tag.ToString(TagRenderMode.SelfClosing))

        End Function

    End Module

End Namespace

Css :

img.field-validation-error
{
    vertical-align:         text-bottom;
    margin-left:            5px;
}

Css css .

. . , imagePath , .

VB ( #), - VB/NET, , Telerik (http://converter.telerik.com/)

+1

, .

If someone wants to hack a version that can / will support client-side validation, she has one! :)

0
source

Turning around on Ed's answer, this means that he can work with models:

public static MvcHtmlString ValidationImageFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
    {
        string propertyName = ExpressionHelper.GetExpressionText(expression);
        string name = helper.AttributeEncode(helper.ViewData.TemplateInfo.GetFullHtmlFieldName(propertyName));

        if (helper.ViewData.ModelState[name] == null || 
            helper.ViewData.ModelState[name].Errors == null || 
            helper.ViewData.ModelState[name].Errors.Count == 0)
        {
            return MvcHtmlString.Empty;
        }

        TagBuilder tag = new TagBuilder("span");
        tag.Attributes.Add("class", "field-validation-error");
        tag.Attributes.Add("data-valmsg-for", name);
        tag.Attributes.Add("data-valmsg-replace", "true");
        return MvcHtmlString.Create(tag.ToString(TagRenderMode.SelfClosing));
    }

I was rendering in a range ... just like MVC does. I have a background image set in a CSS class. Example:

@Html.ValidationImageFor(x => x.FieldNameHere)

NTN

0
source

It is best for MVC developers to change the ModelError.ErrorMessage type to MvcHtmlString or its new instance in .NET4 (HtmlString)

0
source

Source: https://habr.com/ru/post/1714966/


All Articles