[英]How can I reformat my ASP.NET MVC5 error messages to show only the first message in C#
I have the following code that I think will show me each of the errors in my model: 我有以下代码,我认为它将向我展示模型中的每个错误:
@if (!ViewData.ModelState.IsValid)
{
<ul>
@foreach (string key in ViewData.ModelState.Keys)
{
@foreach (var error in ViewData.ModelState[key].Errors)
{
<li>@error.ErrorMessage</li>
}
}
</ul>
}
The code is C# embedded inside a web page. 该代码是C#嵌入在网页内。 Can someone tell me how I could just report the first message and have this reported in a <span>
. 有人可以告诉我如何报告第一条消息并将其报告在<span>
。
@if (!ViewData.ModelState.IsValid)
{
<span>
@ViewData.ModelState.First(x => x.Value.Errors.Any()).Value.Errors.First().ErrorMessage
</span>
}
Of course you could write a custom HTML helper that will do this job instead of ending with such LINQ queries in your views: 当然,您可以编写一个自定义HTML帮助程序来完成此工作,而不是在视图中以此类LINQ查询结尾:
@Html.FirstModelError()
and the helper implementation: 和帮助程序的实现:
public static class HtmlHelpers
{
public static IHtmlString FirstModelError(this HtmlHelper html)
{
var modelState = html.ViewData.ModelState;
if (modelState.IsValid)
{
return MvcHtmlString.Empty;
}
var span = new TagBuilder("span");
string errorMessage = modelState
.First(x => x.Value.Errors.Any())
.Value
.Errors
.First()
.ErrorMessage;
span.SetInnerText(errorMessage);
return new HtmlString(span.ToString());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.