I am currently developing a registration page. When user already exists I want to provide login and reset password links for user in error message for email field. In controller I have:
[HttpPost] public ActionResult Register(RegistrationModel registration) { ... if(userExists) { const string errorMessage = "User already exist. You can <a href="/account/login">login</a> ..."; ModelState.AddModelError("Email", errorMessage); return View("Register", registration); } }
But when I try to output this message in view I do not get what I expect. I get html markup like plain text. I've already tried:
@using(Html.BeginForm()) { <div>@Html.TextBoxFor(m => m.Email) @{ @Html.ValidationMessageFor(m => m.Email) ... @Html.Raw(Html.ValidationMessageFor(m => m.Email)) ... string validationMessage = Html.ValidationMessageFor(m => m.Email).ToString(); @Html.Raw(validationMessage) ... string validationMessage = Html.ValidationMessageFor(m => m.Email).ToHtmlString(); @Html.Raw(validationMessage) ... string validationMessage = Html.ValidationMessageFor(m => m.Email).ToString(); @(new HtmlString(validationMessage)) ... string validationMessage = Html.ValidationMessageFor(m => m.Email).ToHtmlString(); @(new HtmlString(validationMessage)) ... string validationMessage = Html.ValidationMessageFor(m => m.Email).ToString(); @(new MvcHtmlString(validationMessage)) ... string validationMessage = Html.ValidationMessageFor(m => m.Email).ToHtmlString(); @(new MvcHtmlString(validationMessage)) } </div> }
ValidationMessage(HtmlHelper, String) Displays a validation message if an error exists for the specified field in the ModelStateDictionary object.
You can use the standard ASP.NET MVC ValidationSummary method to render a placeholder for the list of validation error messages. The ValidationSummary() method returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object.
The Html. ValidationMessageFor() is a strongly typed extension method. It displays a validation message if an error exists for the specified field in the ModelStateDictionary object.
The ValidationSummary() extension method displays a summary of all validation errors on a web page as an unordered list element. It can also be used to display custom error messages.
@Html.Raw(HttpUtility.HtmlDecode(Html.ValidationMessageFor(m => m.Email).ToHtmlString()))
Isn't pretty though
Found this post while figuring this out myself using ASP.NET Core.
What I ended up doing was adding my part of my validation message in modelstate.AddError(), and separately adding to ViewData the bit that had the Html I wanted to render, like so:
ViewData["myKey"]= "My html";
It feels pretty ugly and there's probably better ways of doing it, but for my very limited needs, this fit the bill nicely.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With