locked
DataAnnotations: ErrorMessage With Images RRS feed

  • Question

  • User-1590999572 posted

    Visual Studio Code 1.48 | .NET Core 3.1

    Hi all

    The following Code does not work:

    ErrorMessage="<img src='Error.png' />")

    It shows: <img src='Error.png' />

    How to display an image instead of a text in the ErrorMessage?

    It is possible to work with Sounds?

    Thank you very much

    Thursday, October 8, 2020 4:25 AM

Answers

  • User-821857111 posted

    Add a method to your PageModel/ViewModel that converts the output of a tag helper (IHtmlContent) to a string:

    public string GetString(IHtmlContent content)
    {
        var writer = new System.IO.StringWriter();
        content.WriteTo(writer, HtmlEncoder.Default);
        return writer.ToString();
    }

    Then in your cshtml file, do this:

     @Html.Raw(System.Net.WebUtility.HtmlDecode(Model.GetString(Html.ValidationMessageFor(model => model.MyProperty))))

    Remember to include the ValidationScriptsPartial too:

    @section scripts{ 
        <partial name="_ValidationScriptsPartial"/>
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, October 9, 2020 7:37 AM

All replies

  • User-939850651 posted

    Hi Skar.2007,

    Skar.2007

    ErrorMessage="<img src='Error.png' />")

    It shows: <img src='Error.png' />

    That's because ASP.NET MVC by default HTML encodes the output of validation helpers. So, your embedded HTML fragment is not treated as actual HTML and no image is displayed.

    You need to set it to html encoding, and then add it to the response stream.

    Please refer to this article: Show Validation Messages Containing Images In ASP.NET MVC.

    Best regards,

    Xudong Peng

    Friday, October 9, 2020 6:47 AM
  • User-821857111 posted

    Add a method to your PageModel/ViewModel that converts the output of a tag helper (IHtmlContent) to a string:

    public string GetString(IHtmlContent content)
    {
        var writer = new System.IO.StringWriter();
        content.WriteTo(writer, HtmlEncoder.Default);
        return writer.ToString();
    }

    Then in your cshtml file, do this:

     @Html.Raw(System.Net.WebUtility.HtmlDecode(Model.GetString(Html.ValidationMessageFor(model => model.MyProperty))))

    Remember to include the ValidationScriptsPartial too:

    @section scripts{ 
        <partial name="_ValidationScriptsPartial"/>
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, October 9, 2020 7:37 AM
  • User-2054057000 posted

    Show Validation Messages Containing Images In ASP.NET MVC

    please refer the above link.

    Saturday, October 10, 2020 1:32 PM