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.

  • http://Website Pavel Kvasnica

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

Recent Posts

  • Time-controlled Azure WebJobs – Azure as easy as it get‘s

        While still in development the Azure WebJob SDK offers some cool features for procession and supply of information. A good example is the sample that observes the Azure Queue and processes an item as soon as it spots one.   Scenario: time-controlled activities – without queue and so on My scenario was quite […]

  • image2021-570x194_thumb.png
    HowTo: Create RSS Feeds with ASP.NET MVC

    I’ve already written about how to consume RSS or Atom Feeds with the SyndicationFeed (in German, sry) but todays post is about how to create or publish an own feed. Beside the age of the feed standard and the much defamation from Facebook, Twitter and Google on RSS/Atom I consider this easy to consume API […]

  • image1997-311x194_thumb.png
    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 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 possible to […]

  • 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 […]

Support us