views:

173

answers:

1

Currently, I'm seeing when the DefaultModelBinder errors because the input is invalid for the type (character in int, invalid date, etc.) I get UI default error summary “Something has gone wrong…” but no specific error message, regarding the specific property that failed conversion.

For example a model property might be a datetime that needs to occur in the future. It might be decorated with a Validator attribute that will give the error “{Property} is a date that needs to occur in the future. Example 4/15/2009”. That message could still be relevant for type conversion errors as well.

How can I give descriptive error messages when a type conversion fails during model binding? Custom model binders, Filters, any examples would be appreciated.

Side note: I’ve been testing with implementations of NHib Val, Castle Val, xVal Lib, and other more manual methods and all of that is working fine for me, but I don’t see these as helping me with the type conversion issues…

UPDATE: I found this exchange involving S. Sanderson (Creator of xVal) on the MVC Codeplex issues list. It discusses the issue I am seeing in more detail... http://aspnet.codeplex.com/WorkItem/View.aspx?WorkItemId=3230

A: 

I personally like the validation to be in the entity with attributes and c# code, so I think the following aproach is at least worth a look:

http://codebetter.com/blogs/david.hayden/archive/2009/01/31/asp-net-mvc-and-validation-using-idataerrorinfo-and-validation-application-block.aspx

It makes the entities implement IDataErrorInfo. Apart from checking each property's validation attributes, you can also check for nulls or invalid casts or any other custom logic like this:

When it does:

public string this[string columnName]
    {
        get 
        {
            return DoValidation(columnName);
        }
    }

You could do something like:

public string this[string columnName]
    {
        get 
        {
            if(columnName=="myDatePropertyName")
            {
               //Add custom logic (invalid casts or whatever)
            }
            return DoValidation(columnName);
        }
    }

What I don't like of this model is having to put the validation error messages in each property, for example, but that's a good kick start.

Anyway this is an example of a model that binds your custom errors to the relevant property, so it will later on be shown on your ValidationSummary.

Hope this helped!

antonioh