The parameter conversion from type 'System.String' to type ''X' failed because no type converter can convert between these types

前端 未结 4 1409
闹比i
闹比i 2021-01-01 10:35

I\'m stumped with this one and your help would be most appreicated.

I get the error:

The parameter conversion from type \'System.String\' to t

4条回答
  •  情歌与酒
    2021-01-01 10:36

    I had the same error but the cause was different from the accepted answer. Adding a custom ModelBinder fixed it for me.

    I created a CData class as described here

    How do you serialize a string as CDATA using XmlSerializer? (it's the last answer unless it got voted up because it's a great solution)

    I serialize my ViewModel to XML. When I set a type in a property in my ViewModel to CData, it will automatically be serialized to a CData section and deserialized to a CData field. (which is great!)

    When I do a post action in my view I want to keep some fields in my ViewModel so they are added as Html.HiddenFor in the form.

    When a submit is done, an error occurs (the one in the title). The model binder tries to bind a string field to a CData field which fails.

    A custom model binder for the CData type fixes this

    public class CDataModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            return new CData(result.AttemptedValue);
        }
    }
    

    Global.asax

     ModelBinders.Binders.Add(typeof(CData), new CDataModelBinder());
    

提交回复
热议问题