英文:
How do I include a clickable hyperlink in ASP.NET MVC Core ModelState error message?
问题
在我的控制器中,有一些自定义验证。我想在ModelState错误消息中提供一个可点击的超链接,当用户点击时,将会带用户前往同一站点的不同页面以进行进一步操作。类似于"错误:请点击此处修复"。以下是控制器的缩减版本:
public IActionResult LaunchItem()
{
var errorMsg = "错误:请点击 <a href=\"https://localhost:44316/Controller/Action\" target=\"_blank\">这里</a> 以修复错误。";
ModelState.AddModelError("", errorMsg);
return View();
}
以下是呈现错误消息的视图部分:
<div asp-validation-summary="All" class="text-danger"></div>
我希望消息显示为"错误:请点击
错误:请点击 <a href="https://localhost:44316/Controller/Action" target="_blank">here</a> 以修复错误
我认为这与编码有关,但我无法弄清楚如何使其工作。
英文:
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.
答案1
得分: 0
以下是翻译好的部分:
在控制器中:
ModelState.AddModelError("", "错误");
ViewBag.FixMessage = string.Format("请点击 <a href={0}>这里</a> 修复", "/Home/Index").ToHtmlString();
在视图中:
// 删除这行
/*@<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>
}
扩展方法:
public static class MyExtension
{
public static HtmlString ToHtmlString(this string str)
{
return new HtmlString(str);
}
}
结果:
英文:
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:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论