简体   繁体   中英

Mimick ValidationSummary For Non-Model Errors

I've seen developers who "exploit" ModelState.AddModelError() to add error messages to ModelState , even though the errors have nothing to do with validation of the Model of the current request.

My take is that instead, a redirect should execute an entirely seperate "Error" action and view to display the error messages. In that case, there would be a dedicated ErrorModel which is presented similarly to how @Html.ValidationSummary presents.

This leads to the question: is there an idiomatic "ErrorModel" structure others use, and/or a popular library / function that takes this model and somewhat imitates the presentation offered by ValidationSummary?

I can make my own ErrorModel and ValidationSummary code (I can even copy the MVC source code), but I'd prefer to use a library or follow a pattern that others use in this situation.

Imho it's fine to use ValidationSummary for this purpose, this is why:

There are 4 versions, two of them important:

Html.ValidationSummary()
Html.ValidationSummary(bool)

The second one is intended to display model errors only, instead of property errors. This implies business logic validation like 'joe can't make appointments on monday'. The first one is intended to display both model errors and property errors.

This is the explanation from Pro ASP.NET MVC3 Framework:

Some of the overloads of the ValidationSummary helper method allow us to specify that only modellevel errors should be displayed. The errors that we have registered with ModelState so far have been property-level errors, meaning there is a problem with the value supplied for a given property and changing that value can address the problem. By contrast, model-level errors can be used when there is some problem arising from an interaction between two or more property values.

So basically I'd say: you're doing just fine, don't bother. Unless you have a specific reason of course.

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