Search code examples
c#asp.net-mvcasp.net-coremodelstate

How do I include a clickable hyperlink in ASP.NET MVC Core ModelState error message?


In my controller, there are some custom validations. I want to provide a clickable hyperlink in the ModelState error message, that when clicked, will take the user to different page of the same site for further actions. Something like "Error: please click here to fix it". Here is the scaled down version of the controller.

public IActionResult LaunchItem()
{      
    var errorMsg = @"Error: Please click <a href=""https://localhost:44316/Controller/Action"" target=""_blank"">here</a> to fix error.";
    ModelState.AddModelError("", errorMsg);
    return View();
}

Here is the portion of the view that presents the error message.

<div asp-validation-summary="All" class="text-danger"></div>

I would like the message to show with the "here" being the clickable hyperlink:

Error: Please click <here> to fix error

Instead, the message include the whole anchor text, like this:

Error: Please click <a href="https://localhost:44316/Controller/Action" target="_blank">here</a> to fix error

I think this has something to do with encoding but I can't figure out how to make it work.


Solution

  • You could try as below:

    In controller:

    ModelState.AddModelError("", "Error");
     ViewBag.FixMessage = String.Format("Please click <a href={0}>Here</a> to fix", "/Home/Index").ToHtmlString();
    

    In View:

    //remove it
    @*<div asp-validation-summary="ModelOnly" class="text-danger" ></div>*@
    
                @if (!ViewData.ModelState.IsValid&& ViewData.ModelState[""]?.Errors.Count>0)
                {
                    <div class="text-danger validation-summary-errors">
                        @ViewBag.FixMessage;
                    </div>
                    
                }
    

    Extension :

    public static class MyExtension
        {
            public static HtmlString ToHtmlString(this String str)
            {
                return new HtmlString(str);
            }
        }
    

    Result:

    enter image description here