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 Code Inside Team

Learn more about our team.

Comment on this post

Recent Posts

  • Git-Pull Request mergen for beginners

    My project “KnowYourStack.com” (the working title was BizzBingo – a detailed blogpost will follow soon) lays on GitHub and I’ve recognized a Problem where Daniel Lang helped me a lot. At the end he created a Fork for my Project and laid a Pull Request: The question is: How do I transfer the changes to ...

  • Carriage Return / new line in Textareas

      A little task: each new text line (Carriage Return/ if you press enter ) in a Textarea should be an element on a list – so what’s the easiest way? Actual a basic element in the web and the user make aware distributions – so it would be fair to dignify it. Little MVC ...

  • WebDev Playground: dabblet.com for HTML/CSS, jsfiddler.com for JS & HUrl.it for REST

      What was reserved for mighty Desktop Apps in the past is now coming closer to the web. I’ve going to present three tools to you which are very useful for web developer. At least all the tools are quite cool in there functionality. Playground for HTML/CSS If you need a quick Playground for CSS ...

  • image1452_thumb.png
    Javascript to Dart Translator

      Dart, a Google Javascript alternative was presented a few months ago and the web developer scene are a little bit unsure about the usability of Dart. To declare the language Google has translated the Javascript basics into Dart. The result is this “Translator”. In my opinion the name doesn’t find that well because it’s ...

  • image1366-570x194.png
    Twitter Bootstrap as UI-kit

      HTML and CSS are not foreign words for me but I regret, I’m not a Web designer – I see myself as a webdeveloper. But at least a dressy side is a must. But thank good there are some ready “Systems”. Twitter Bootstrap Twitter Bootstrap is a Toolkit for every kind of Web applications. ...

Support us