How to fix the infamous "Unable to cast object of type 'System.Int32' to type 'System.String' error in asp.net mvc How to fix the infamous "Unable to cast object of type 'System.Int32' to type 'System.String' error in asp.net mvc

How to fix the infamous “Unable to cast object of type ‘System.Int32’ to type ‘System.String’ error in asp.net mvc

The Problem

You have created a lovely model in asp.net mvc 4, using Entity Framework and a whole host of attributes.  One of the properties of your model looks like this

[Required]
[Display(Name = “Expiration Month (MM)”)]
[StringLength(2,ErrorMessage = “You must enter two digits”, MinimumLength = 1)]
[Range(1,12, ErrorMessage = “You must enter a valid month”)]
public int ExpirationMonth { get; set; }

That yields an error of

Unable to cast object of type ‘System.Int32’ to type ‘System.String

When the form is submitted, but not when the object is created (which is a bit odd)

The Cause

It turns out that you cannot use the StringLength data attribute on an int data type.  You would think you could since all you are actually interested in with that data attribute is the number of digits, but the data gods have decreed that you can’t.

The Solution

Just comment out StringLength and use the Range Attribute.

 

Written By Steve French

 

2 responses to “How to fix the infamous “Unable to cast object of type ‘System.Int32’ to type ‘System.String’ error in asp.net mvc”

Leave a Reply

Your email address will not be published. Required fields are marked *






Copyright 2011 Digital Tool Factory. All Rights Reserved. Powered by raw technical talent. And in this case, WordPress.