Fix: the value ‚x‘ is not valid for Foo in ASP.NET MVC

image1441.png

 

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.

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

About the author

Written by

Learn more about our team.

One Response

  1. Thank you for the solution. It helped and works as expected.

    Reply

Comment on this post

Recent Posts

  • How to access an Azure Website with the local IIS Manager

      Since the end of February it is possible to access an Azure Website with the IIS Manager. Although the Azure Management site offers some information’s there are more details visible at the IIS Manager.   For the connection you will need an IIS Manager and the IIS Manager for Remote Administration Extension. It’s also […]

  • image1929-570x143_thumb.png
    Create and validate own Json-Web-Tokens (JWTs)

    If you are interested in web authentication you probably have heard about JSON Web tokens (JWT). What is a JWT? Maybe I’m not using the correct security termination but however: JWTs are used to exchange claims between two systems. For example: You want to log on to a service (like Facebook, Twitter, etc.) and want […]

  • Micro-Optimization: how to shrink or „embed“ pictures

      I’m currently working on the “CodeInside Dashboard” and since the page structure isn’t that difficult it should be possible to fulfill all of Google Pagespeed or Yahoos YSlow recommendations. One of the rules was to optimize the 4 PNGs that are embedded on the page.   Before – without optimization: Below you can see […]

  • image1979-570x194.png
    Move to Windows Azure – VMs, Word Press Migration, DNS changes

    Since mid January this blogs runs on a WordPress installation in an Azure VM. Because I always thought that the subject is quite complicated this blogpost offers a view behind the scenes. Why this move? So far this blog (both German and English Version) runs on a hoster somewhere in Germany. The main problem with this […]

  • Windows Azure Active Directory – CRUD for users and groups

      Windows Azure Active Directory? If you are not informed about the subject I recommend you to have a look on this Azure Info site. Which resources are there? The Azure AD contains the following entities: - Users - Groups - Contacts - Roles Access to the directory or on the “directory graph” Although the […]

Support us