jeudi 5 novembre 2015

MVC 5 checkbox input validation / error handling

I have a problem validating a bool value in my ViewModel displayed as a checkbox.

ViewModel:

public class UserModel
{
    public bool Newsletter { get; set; }
}

The View:

@Html.CheckBoxFor(m => m.Newsletter)

I have been trying to build a custom ValidationAttribute to make sure that only true/fales values can be sent to the controller. If someone changes the value of the checkbox, to lets say "asdfg", the submit of the form will result in a 500 error with the following error: System.InvalidOperationException! The parameter conversion from type 'System.String' to type 'System.Boolean' failed. See the inner exception for more information.

I have been trying to find a way to avoid this server error, but it seemas that MVC craches before ValidationAttribute is applied.

The only solution to handle this was to use the OnException in the controller. Does anyone know a better way to handle this?

    protected override void OnException(ExceptionContext filterContext)
    {
        if (filterContext.Exception is InvalidOperationException)
        {
            // Handle this exception here
        }

        base.OnException(filterContext);
    }




Aucun commentaire:

Enregistrer un commentaire