Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - Why is ValidationSummary(true) displaying an empty summary for property errors?

I am having a slight issue with the use of ValidationSummary(true) to display model level errors. If the ModelState does not contain model errors (i.e. ModelState.AddModelError("", "Error Description")) but contains property errors (added using data annotations) it displays the validation summary with no error information (when you view the source). My css is therefore displaying an empty red box like so:

enter image description here

If there are no property errors then no validation summary is displayed. With ValidationSummary(true) I would expect it to only display validation errors if there are model errors. What have I misunderstood?

I have a basic project as follows:

Controller:

public class HomeController : Controller
{
    public ViewResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(IndexViewModel model)
    {
        return View();
    }
}

Model:

public class IndexViewModel
{
    [Required]
    public string Name { get; set; }
}

View:

@model IndexViewModel

@Html.ValidationSummary(true)

@using(@Html.BeginForm())
{
    @Html.TextBoxFor(m => m.Name)
    <input type="submit" value="submit" />
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
@if (ViewContext.ViewData.ModelState.Where(x => x.Key == "").Any())
{
    @Html.ValidationSummary(true, null, new { @class = "ui-state-error" })
}

This checks if there are any model wide errors and only renders the summary when there are some.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...