views:

104

answers:

1

What pattern can I use to display errors on an MVC 2 view that are not related to a single property?

For example, when I call a web service to process form data, the web service may return an error or throw an exception. I would like to display a user-friendly version of that error, but have no logical means to relate the error to any given property of the model.

UPDATE:

Trying to use this code as suggested, but no summary message is displayed:

MyPage.spark:

Html.ValidationSummary(false, "Oopps it didn't work.");

Controller:

ViewData.ModelState.AddModelError("_FORM", "My custom error message.");
// Also tried this: ViewData.ModelState.AddModelError(string.Empty, "My custom error message.");
return View();

UPDATE 2

What does this mean?

next to each field.

Instead of always displaying all validation errors, the Html.ValidationSummary helper method has a new option to display only model-level errors. This enables model-level errors to be displayed in the validation summary and field-specific errors to be displayed next to each field.

Source: http://www.asp.net/learn/whitepapers/what-is-new-in-aspnet-mvc#_TOC3_14

Specifically, how does one add a model level error (as opposed to a field-specific error) to the model?

UPDATE 3:

I noticed this morning that Html.ValidationSummary is not displaying any errors at all, not even property errors. Trying to sort out why.

+1  A: 

Simply adding a custom error to the ModelState object in conjunction with the ValidationSummary() extension method should do the trick. I use something like "_FORM" for the key... just so it won't conflict with any fields.

As far as patterns go, I have it setup so that my Business Logic Layer (called via services from the controller) will throw a custom exception if anything expected goes wrong that I want to display on the view. This custom exception contains a Dictionary<string, string> property that has any errors that I should add to ModelState.

HTHs,
Charles

Charlino
@Charlino: I'm doing something like what you suggest. Could you have a look at my updated post and let me know if you see a problem?
Eric J.