19

I've been stuck trying to debug this issue. I believe the error Is occurring when I am trying to populate a drop down list.

 IEnumerable<Customer> values = db.Customers.SqlQuery("SELECT * FROM Customer").ToList().Cast<Customer>();

 IEnumerable<SelectListItem> items =
     from value in values
     select new SelectListItem
     {
         Text = value.CustomerID.ToString(),
         Value = value.CustomerID.ToString(),
     };

 ViewBag.Accounts = items;

Stack Trace

[InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'.]

System.ComponentModel.DataAnnotations.StringLengthAttribute.IsValid(Object value) +46
   System.ComponentModel.DataAnnotations.ValidationAttribute.IsValid(Object value, ValidationContext validationContext) +115
   System.ComponentModel.DataAnnotations.ValidationAttribute.GetValidationResult(Object value, ValidationContext validationContext) +29
   System.Web.Mvc.<Validate>d__15.MoveNext() +161
   System.Web.Mvc.<Validate>d__1.MoveNext() +311
   System.Web.Mvc.DefaultModelBinder.OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) +136
   System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +66
   System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +1314
   System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +416
   System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +317
   System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +117
   System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) +446
   System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
   System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +302
   System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +30
   System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
   System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +382
   System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
   System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +317
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +15
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +71
   System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +249
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
5
  • The problem could be in your Cast. Any reason why you have the "Select *"? Why not just db.Customers.ToList() since you want the whole list?
    – Jason
    Oct 6, 2013 at 3:27
  • Whats the problem with the cast? it wont allow me to keep It as just Text = value.CustomerID. Regarding the select * I fix that, that was a good point
    – kayze
    Oct 6, 2013 at 3:39
  • I meant your Cast to the Customer object, which should be unnecessary if you avoid the SqlQuery. Populating the list using ToString() should be fine.
    – Jason
    Oct 6, 2013 at 3:44
  • Thanks but still no luck
    – kayze
    Oct 6, 2013 at 3:59
  • I've posted the trace
    – kayze
    Oct 6, 2013 at 4:40

2 Answers 2

68

Judging from the exception message your Customer class looks something like this...

public class Customer
{
    [StringLength(4)]
    public int CustomerID { get; set;}
}

Notice that you can't use StringLength on an int property.

Get rid of the StringLength and the validation exceptions should go away.

6
  • Thanks! That's my problem too. Then how can I valid thing like this? with a Regex?
    – equiman
    Jun 5, 2015 at 19:45
  • 1
    @equiman this isn't the place to ask a follow up question, I can't answer you fully in a comment, nor can you properly ask the question. However you might be looking for the [RangeAttribute]. Otherwise it is likely your int isn't an int.
    – Aron
    Jun 5, 2015 at 20:04
  • Thanks hehehe... I changed the type of the property in the database side and forgot to change it inside the partial class in the code. Before changing it to int it was a string and it sure had the StringLength data annotation there. Nov 6, 2015 at 17:23
  • 4
    That's funny. I had a similar problem due to a MaxLength attribute over a property that used to be a string, but was then refactored into its own view model. Sep 21, 2016 at 14:37
  • 2
    instead of using "StringLength(4)" you can simply use "Range(int min,int max)" Attribute. Oct 13, 2017 at 7:48
0

I sat on this problem for hours, Property gets populated in OnGet, but no options were generated in final HTML rendering. Tried to generate Elements with foreach in View, tried to generate a List via Linq from Entity and populate that to the view, nothing worked.

Restarted the PC, everything works fine.

1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    May 30 at 15:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.