Reputation: 117146
I have an error and I would like to add a link to it
ModelState.AddModelError(string.Empty, "You must have a confirmed email to log in.");
What I want to do is add a link to the SendEmailConfirmationMail action so I can resend it to them, in the event it was lost.
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> SendEmailConfirmationMail(string email, string returnUrl = null)
{
// Stuff removed
}
What I have tried
ModelState.AddModelError(string.Empty,
$"You must have a confirmed email to log in. Click to resend conformation email <a href=account/SendEmailConfirmationMail?Email={model.Email}&returnUrl={returnUrl}> resend</a>");
and
ModelState.AddModelError(string.Empty, $"<a href=\"{Url.Action("SendEmailConfirmationMail", "Account", new { Email = model.Email, returnUrl = returnUrl })}\">Click me</a>");
This doesnt work very well.
I am open to other ideas if I am doing this wrong. I am still learning asp.net mvc.
From the view how its shown
@if (error != null)
{
<strong>
<em> : @Html.Raw(error)</em>
</strong>
}
Update:
When i inspect the page. It looks like the html is getting replaced.
<li><a href="/Account/[email protected]">Click me</a></li>
Upvotes: 0
Views: 965
Reputation: 1275
Your error
is an Html encoded string, you need to use HttpUtility.HtmlDecode
to decode it first
<em> : @Html.Raw(HttpUtility.HtmlDecode(error))</em>
Upvotes: 2
Reputation: 13640
If you are in control of the view which displays the error, it would be better to format the error in the view itself since it's representation logic.
Add the model error in controller:
ModelState.AddModelError("EmailNotConfirmedError", string.Empty); // You can specify the error message or ignore it
Check for this specific error in the view:
<div>
@if (ViewData.ModelState.ContainsKey("EmailNotConfirmedError"))
{
<em>You must have a confirmed email to log in. Click to resend conformation email @Html.ActionLink("resend", "SendEmailConfirmationMail", "Account")</em>
}
</div>
Upvotes: 5
Reputation: 2241
Rather use @Url.Action()
method to get the URL
You can use it like this:
@Url.Action("MethodName","ControllerName",new{param1 = param1value});
UPDATE To get your URL use this code:
var url = Url.Action("Account","SendEmailConfirmationMail",new{Email=model.Email,returnUrl = returnUrl;
ModelState.AddModelError(string.Empty,
$"You must have a confirmed email to log in. Click to resend conformation email {url})");
Upvotes: 1