如果 mvc 视图中验证失败,如何添加链接元素以及验证消息

问题描述 投票:0回答:2

我有要求,如果电子邮件字段验证(例如电子邮件)已在使用,那么它显示验证消息电子邮件现在已与此验证消息一起使用,我想附加登录链接我该怎么做

<div>
  <input asp-for="Email" type="text" placeholder="Email" class="form-control" />
 </div>
<span asp-validation-for="Email" id="err" class="text-danger"></span>
<a  asp-area="" asp-controller="Account" asp-action="Login" asp-route-aname="indiaRegion">login</a>
Any Help That Grate For Me How Can I append The Link At Time Of email Validation Fail  I have Remote Email Verification For Already In Use 
asp.net-core model-view-controller
2个回答
1
投票

尝试使用远程验证并在验证消息中添加

<a>
标签。检查以下代码:

用户视图模型:

    [Remote(action: "VerifyEmail", controller: "Home")]
    public string Email { get; set; }

视图中的代码:

        <div class="form-group">
            <label asp-for="Email" class="control-label"></label>
            <input asp-for="Email" class="form-control" />
            <span asp-validation-for="Email" class="text-danger"></span> 
        </div> 

控制器中的代码:

    [AcceptVerbs("GET", "POST")]
    public IActionResult VerifyEmail(string email)
    { 
        //Generate the login url:
        string loginurl = string.Format("{0}://{1}/{2}", Request.Scheme, Request.Host, "Identity/Account/Login");
        if (_userService.VerifyEmail(email))
        {
            return Json($"Email {email} is already in use, click the <a href='" + loginurl + "'> here </a> to login.");
        }

        return Json(true);
    }

测试截图:

enter image description here


0
投票

我发现我可以将错误消息转换为字符串,然后对其进行替换:

var error = Html.ValidationMessage("email")?.ToHtmlString();

if (!string.IsNullOrWhiteSpace(error))
{
    error = error.Replace("[login link]", "<a href=\"/login\">login</a>")

    @Html.Raw(error)
}

© www.soinside.com 2019 - 2024. All rights reserved.