logo
down
shadow

ASP.NET MVC Bug with Model Binding: "Specified cast is not valid" when no data provided for dictionary


ASP.NET MVC Bug with Model Binding: "Specified cast is not valid" when no data provided for dictionary

By : Kamakura Frank
Date : November 22 2020, 10:33 AM
hop of those help? It sure looks like you're running into that bug.
The bug was fixed over a year ago. Have you tried upgrading to MVC 5? That CodePlex bug report has a .cs file attached that provides a fixed dictionary binder. You can incorporate it using this in App_Start:
code :
ModelBinder.Binders.DefaultBinder = new DefaultDictionaryBinder();
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web.Mvc;

/// <summary>
/// ASP.NET MVC Default Dictionary Binder, with a dictionary that doesn't bind your
/// route parameters when no values are passed
/// Adapted from: https://github.com/loune/MVCStuff/blob/master/Extensions/DefaultDictionaryBinder.cs
/// </summary>
public class FixedDictionaryBinder : DefaultModelBinder
{
    readonly IModelBinder _nextBinder;

    /// <summary>
    /// Create an instance of DefaultDictionaryBinder.
    /// </summary>
    public FixedDictionaryBinder()
        : this(null)
    {
    }

    /// <summary>
    /// Create an instance of DefaultDictionaryBinder.
    /// </summary>
    /// <param name="nextBinder">The next model binder to chain call. If null, by default, the DefaultModelBinder is called.</param>
    public FixedDictionaryBinder(IModelBinder nextBinder)
    {
        _nextBinder = nextBinder;
    }

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        Type modelType = bindingContext.ModelType;

        if (modelType.AssemblyQualifiedName != null && modelType.AssemblyQualifiedName.StartsWith("System.Collections.Generic.IDictionary`2"))
        {
            object result = null;

            var ga = modelType.GetGenericArguments();
            var valueBinder = Binders.GetBinder(ga[1]);

            foreach (var key in GetValueProviderKeys(controllerContext))
            {
                if (!key.StartsWith(bindingContext.ModelName + "[", StringComparison.InvariantCultureIgnoreCase))
                    continue;

                var endbracket = key.IndexOf("]", bindingContext.ModelName.Length + 1, StringComparison.InvariantCultureIgnoreCase);
                if (endbracket == -1)
                    continue;

                object dictKey;
                try
                {
                    dictKey = ConvertType(key.Substring(bindingContext.ModelName.Length + 1, endbracket - bindingContext.ModelName.Length - 1), ga[0]);
                }
                catch (NotSupportedException)
                {
                    continue;
                }

                var innerBindingContext = new ModelBindingContext
                                              {
                                                  ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => null, ga[1]),
                                                  ModelName = key.Substring(0, endbracket + 1),
                                                  ModelState = bindingContext.ModelState,
                                                  PropertyFilter = bindingContext.PropertyFilter,
                                                  ValueProvider = bindingContext.ValueProvider
                                              };
                var newPropertyValue = valueBinder.BindModel(controllerContext, innerBindingContext);

                if (result == null)
                    result = CreateModel(controllerContext, bindingContext, modelType);

                if (!(bool)modelType.GetMethod("ContainsKey").Invoke(result, new [] { dictKey }))
                    modelType.GetProperty("Item").SetValue(result, newPropertyValue, new [] { dictKey });
            }

            return result;
        }

        return _nextBinder != null
                   ? _nextBinder.BindModel(controllerContext, bindingContext)
                   : base.BindModel(controllerContext, bindingContext);
    }

    private static IEnumerable<string> GetValueProviderKeys(ControllerContext context)
    {
        var keys = new List<string>();
        keys.AddRange(context.HttpContext.Request.Form.Keys.Cast<string>());
        keys.AddRange(((IDictionary<string, object>)context.RouteData.Values).Keys);
        keys.AddRange(context.HttpContext.Request.QueryString.Keys.Cast<string>());
        keys.AddRange(context.HttpContext.Request.Files.Keys.Cast<string>());
        return keys;
    }

    private static object ConvertType(string stringValue, Type type)
    {
        return TypeDescriptor.GetConverter(type).ConvertFrom(stringValue);
    }
}


Share : facebook icon twitter icon
SqlDataSource throwing "Specified cast is not valid" error on data pulled from Oracle

SqlDataSource throwing "Specified cast is not valid" error on data pulled from Oracle


By : Sameera Maduranga
Date : March 29 2020, 07:55 AM
it helps some times This is a problem involving conversion of Oracle data types to .Net types. Entity Framework 3 and 4 had a similar problem. If you specified an Oracle type as Number(10) it was interpreted as a .Net Float.
I suspect this is a similar issue with .Net casting the Oracle number into a float instead of a decimal. This answer has more details.
Structured Data Testing Tool: "The value provided for image must be a valid URL."

Structured Data Testing Tool: "The value provided for image must be a valid URL."


By : kui wang
Date : March 29 2020, 07:55 AM
it helps some times After a lot of tries I removed the dash from the image name and now It's working without errors. I didn't find this resolution anywhere and It's not in the documentation or at least I didn't find it. Still this looks like a very suspicious cause but...
Swift 3 Core Data - NSExpression forFunction: "sum:" throws error ("could not cast dictionary to Day"

Swift 3 Core Data - NSExpression forFunction: "sum:" throws error ("could not cast dictionary to Day"


By : Dashrath Bhojwar
Date : March 29 2020, 07:55 AM
Hope that helps I have days and tasks. A day has many tasks. Every task has an attribute called "points" and I want to sum all points of the tasks of the current day. I used the code below (found in the book Core Data by tutorials, swift 2 version) and tried to modify it for swift 3 (I also added a predicate, but that's not important). But when I run this code, I get this error: , This solves my problem:
code :
let sumRequest: NSFetchRequest<NSFetchRequestResult> = Day.fetchRequest()
Oracle data type "Specified Cast is not valid" in C# Entity Framework

Oracle data type "Specified Cast is not valid" in C# Entity Framework


By : Michael Austin
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , The decimal type has a smaller range than the number you are attempting to set it to, hence the error. The Decimal types value is its precision, MS Reference articles state that its better used for financial calculations.
https://docs.microsoft.com/en-us/dotnet/articles/csharp/language-reference/keywords/decimal
How to fix "Specified Cast Is Not Valid" error when retrieving data from table to confirm if record exists?

How to fix "Specified Cast Is Not Valid" error when retrieving data from table to confirm if record exists?


By : user2595482
Date : March 29 2020, 07:55 AM
I wish did fix the issue. You should try to hold the ExecuteScalar value to an object type variable, then find out in debugging what is its type, and then apply the cast. As is mentioned by @Alex K in the comments section. Hope it works.
Related Posts Related Posts :
  • Best Way to reuse code inside my Controller action method
  • BEM and asp.net mvc
  • RazorPDF save pdf file to server directory in MVC4
  • Controller Unit Testing with model validation
  • How to bind input field to editfor model MVC
  • How can I restrict access to a view only to two specific users each time in MVC?
  • How to modify CRUD operations with Entity Framework in .NET MVC application
  • ModelBinding Issue with a Struct
  • issue in adding elements into a list in mvc
  • IActionFilter class can only find physical attributes, not ones added in GlobalFilters config
  • How to reuse class in models without using validation for all of them
  • How to set routing to have some controller actions handled by angular
  • ads while debugging mvc website
  • Does editing a Web.config file trigger an overlapping recycle or a start+stop of the application pool?
  • How can i delete multi selected records using checkbox in Kendo Grid?
  • 404.15 not found MVC4 RazorJS
  • Passing selected value from the radio buttons to the controller in MVC
  • TFS:The "Microsoft.Reporting.RdlCompile" task could not be loaded from the assembly Microsoft.ReportViewer.Web
  • ViewModel in postback to controller is null
  • Get the user id of a username identity 2.0
  • Don't validate date fields on MVC
  • Add class and default value to MVC dropdown that isn't linked to model
  • Passing values from the view to the controller in MVC
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org