简体   繁体   中英

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. Can someone tell me how I could just report the first message and have this reported in a <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.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());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM