The html tags are displayed as plain text in asp.net core mvc razor pages

Sherpa 181 Reputation points
2024-05-21T18:19:57.5566667+00:00

I am working on Asp.Net Core 6.0 MVC Razor pages. On the Login.cshtml page, I want to show the following error message when the user tries to login with in invalid credential: Invalid: <b>User Name</b> and/or <b>Password</b>. The problem is this message is displayed as a text instead of an html with the "User Name" and "Password" in bold. The following is my C# code in Login.cshtml.cs

var invalidLogin = await LockOut(Input.UserUserName, Input.Password);

if (!string.IsNullOrEmpty(invalidLogin))

{

   invalidLogin = WebUtility.HtmlEncode(invalidLogin);

   ModelState.AddModelError(string.Empty, invalidLogin);



   return Page();

}

As shown above, I even tried to html encode the message. Still it's displayed as a text, "Invalid: <b>User Name</b> and/or <b>Password</b>." However, since the div in which it is displayed has the class, "text-danger" the color of the text is correctly set as red.

Based on Google search, I have verified that the page source has this line at the top: <!DOCTYPE html>

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,256 questions
{count} votes

Accepted answer
  1. Ping Ni-MSFT 2,405 Reputation points Microsoft Vendor
    2024-05-22T01:45:35.88+00:00

    Hi @Sherpa,

    Firstly, no need encode the error message as HTML(no need use WebUtility.HtmlEncode):

    invalidLogin ="Invalid: <b>User Name</b> and/or <b>Password</b>";
    ModelState.AddModelError(string.Empty, invalidLogin);
    

    In your Razor Pages .cshtml file, get the ModelState with key name which is empty string here, then use @Html.Raw() to interpret the HTML tags:

    @if (ModelState[""] != null && ModelState[""]?.Errors.Count!=0)
    {
        var error = ModelState[""]?.Errors.First().ErrorMessage;
        @Html.Raw(error)
    }
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
    Best regards,
    Rena

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 58,441 Reputation points
    2024-05-21T19:51:42.47+00:00

    the model error collection does not support markup. the string will aways be html encoded before display, which will convert "<b>" to "&lt;b&gt;" which the browser displays as "<b>"