23 January 2012 value; ASP.NET MVC CI Team

 

To get files into the MVC Controller Modelbinding from MVC is a clever method.

But in fact it is a little bit complicated to set the error message if the connection failed.

Example:

public class RegisterModel
    {
		...

        [Required]
        [DataType(DataType.EmailAddress)]
        [Display(Name = "Email address")]
        public string Email { get; set; }

        [Required]
        [Display(Name = "Age")]
        public int Age { get; set; }

		...
    }

This is the default model for the registration in the ASP.NET MVC project draft. I’ve added a Property “Age” from the Typ “int”. This have to be mentioned in the View as well:

 ...
			<div class="editor-label">
                @Html.LabelFor(m => m.Age)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.Age)
                @Html.ValidationMessageFor(m => m.Age)
            </div>
			...

Problem: What happens if the user enters letters instead of numbers?

Everything is alright as long as the ClientValidation is on:

image

If it’s off you will receive this error message:

image

The error message “The vaule ‘Test’ is not valid for Age.” Will be written directly into the ModelState:

image1439

Unfortunately it’s not that easy to change this message – all kinds of languages will be ignored. That doesn’t look nice on a German side.

Fix: create a resource file

You need to create a Resource file at the App_GlobalResources and add a “PropertyValuenvalid” with the proper text:

image

Link the Resource file to the Global.asax:

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            DefaultModelBinder.ResourceClassKey = "Errors"; <-- lookup in Errors.resx

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }

Result:

image1441

Background:

It’s not possible to run every kind of validation logic because the Framework isn’t able to attach the Property. Interestingly the reaction of the Framework is different if you try to allocate a higher number to the Int. In this case the ModelState receives an Exception you are able to catch. Also a validation could grip. I only have this problem in connection with String-entries.