Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6800213
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T18:56:32+00:00 2026-05-26T18:56:32+00:00

I try to serialize the ModelStateDictionary to a XML string. I tried with the

  • 0

I try to serialize the ModelStateDictionary to a XML string. I tried with the .net XML serialization class like this:

        XmlSerializer serializer = new XmlSerializer(typeof(ModelStateDictionary));
        TextWriter textWriter = new StreamWriter("c:\\files\\text.xml");
        serializer.Serialize(textWriter,this.ModelState);
        textWriter.Close();

The result was:

<?xml version="1.0" encoding="utf-8"?>
   <ArrayOfKeyValuePairOfStringModelState xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <KeyValuePairOfStringModelState />
   <KeyValuePairOfStringModelState />
   <KeyValuePairOfStringModelState />
   <KeyValuePairOfStringModelState />
   <KeyValuePairOfStringModelState />
   <KeyValuePairOfStringModelState />
   <KeyValuePairOfStringModelState />
   <KeyValuePairOfStringModelState />
   <KeyValuePairOfStringModelState />
   <KeyValuePairOfStringModelState />
   <KeyValuePairOfStringModelState />
   <KeyValuePairOfStringModelState />
   <KeyValuePairOfStringModelState />
   <KeyValuePairOfStringModelState />
   <KeyValuePairOfStringModelState />
</ArrayOfKeyValuePairOfStringModelState>

So to try it in a different way I used SharpSerializer with this code:

SharpSerializer serializer = new SharpSerializer();
serializer.Serialize(ModelState, "c:\\files\\text.xml");

This gave me an error:

Unable to cast object of type 'System.Web.Mvc.ModelStateDictionary' to type 'System.Collections.ICollection'.

With this stacktrace:

    [InvalidCastException: Unable to cast object of type 'System.Web.Mvc.ModelStateDictionary' to type 'System.Collections.ICollection'.]
   Polenter.Serialization.Serializing.PropertyFactory.parseCollectionItems(CollectionProperty property, TypeInfo info, Object value) +121
   Polenter.Serialization.Serializing.PropertyFactory.fillCollectionProperty(CollectionProperty property, TypeInfo info, Object value) +75
   Polenter.Serialization.Serializing.PropertyFactory.CreateProperty(String name, Object value) +679
   Polenter.Serialization.SharpSerializer.Serialize(Object data, Stream stream) +196
   Polenter.Serialization.SharpSerializer.Serialize(Object data, String filename) +111
   Getronics.Web.Portal.Controllers.BaseCiController`1.Create(String btnaction, TRecordType dto) in C:\projects\Getronics\Getronics.Web.Portal\Controllers\BaseCiController.cs:58
   lambda_method(Closure , ControllerBase , Object[] ) +228
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
   System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
   System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
   System.Web.Mvc.Controller.ExecuteCore() +116
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
   System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
   System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
   System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
   System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8963149
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184

So no luck here. Though I really nead to serialize the modelstate. Does anyone know how to get the SharpSerializer to work with a Dictionary object? Or maybe a different serializer?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T18:56:32+00:00Added an answer on May 26, 2026 at 6:56 pm

    Here’s a snippet of how to use the following Dictionary wrapper to serializes out the ModelStateDictionary.

    XmlSerializer serializer = new XmlSerializer(typeof(SerializableDictionaryWrapper<string, ModelState>));
    TextWriter textWriter = new StreamWriter("c:\\files\\text.xml");
    serializer.Serialize(textWriter,new SerializableDictionaryWrapper<string, ModelState>(this.ModelState));
    textWriter.Close();
    

    Here’s a Dictionary wrapper class which will make dictionaries compatible with the XmlSerializer.

    /// <summary>
    /// The XmlSerializer doesn't know how to serialize dictionaries and will refuse
    /// to serialize anything that implements IDictionary.  This class can be used
    /// to temporarily wrap a dictionary for the serialization process.
    /// </summary>
    [XmlRoot("DICTIONARY")]
    public class SerializableDictionaryWrapper<TKey, TValue> : IXmlSerializable
    {
      #region Data
    
      private IDictionary<TKey, TValue> m_dictionary = null;
    
      #endregion
    
      #region Properties
    
      /// <summary>
      /// Gets or sets the wrapped dictionary.
      /// </summary>
      /// <value>The wrapped dictionary.</value>
      public IDictionary<TKey, TValue> WrappedDictionary
      {
        get { return m_dictionary; }
        set { m_dictionary = value; }
      }
    
      #endregion
    
      #region Constructors
    
      /// <summary>
      /// 
      /// </summary>
      public SerializableDictionaryWrapper()
      {
    
      }
    
      /// <summary>
      /// 
      /// </summary>
      /// <param name="dict"></param>
      public SerializableDictionaryWrapper(IDictionary<TKey, TValue> dict)
      {
        m_dictionary = dict;
      }
    
      #endregion
    
      #region IXmlSerializable Members
    
      /// <summary>
      /// This property is reserved, apply the <see cref="T:System.Xml.Serialization.XmlSchemaProviderAttribute"></see> to the class instead.
      /// </summary>
      /// <returns>
      /// An <see cref="T:System.Xml.Schema.XmlSchema"></see> that describes the XML representation of the object that is produced by the <see cref="M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)"></see> method and consumed by the <see cref="M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)"></see> method.
      /// </returns>
      public System.Xml.Schema.XmlSchema GetSchema()
      {
        return null;
      }
    
      /// <summary>
      /// Generates an object from its XML representation.
      /// </summary>
      /// <param name="reader">The <see cref="T:System.Xml.XmlReader"></see> stream from which the object is deserialized.</param>
      public void ReadXml(System.Xml.XmlReader reader)
      {
        XmlSerializer key_serializer = new XmlSerializer(typeof(TKey));
        XmlSerializer value_serializer = new XmlSerializer(typeof(TValue));
    
        bool was_empty = reader.IsEmptyElement;
    
        m_dictionary = null;
        string type_name = reader.GetAttribute("type");
        if (type_name != null)
        {
          Type type = Type.GetType(type_name, false);
          if (type != null)
          {
            m_dictionary = Activator.CreateInstance(type) as IDictionary<TKey, TValue>;
          }
        }
    
        if (m_dictionary == null)
        {
          m_dictionary = new Dictionary<TKey, TValue>();
        }
    
        reader.Read();
    
        if (was_empty)
        {
          return;
        }
    
        while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
        {
          reader.ReadStartElement("item");
    
          reader.ReadStartElement("key");
          TKey key = (TKey)key_serializer.Deserialize(reader);
          reader.ReadEndElement();
    
          reader.ReadStartElement("value");
          TValue value = (TValue)value_serializer.Deserialize(reader);
          reader.ReadEndElement();
    
          m_dictionary.Add(key, value);
    
          reader.ReadEndElement();
          reader.MoveToContent();
        }
        reader.ReadEndElement();
      }
    
      /// <summary>
      /// Converts an object into its XML representation.
      /// </summary>
      /// <param name="writer">The <see cref="T:System.Xml.XmlWriter"></see> stream to which the object is serialized.</param>
      public void WriteXml(System.Xml.XmlWriter writer)
      {
        XmlSerializer key_serializer = new XmlSerializer(typeof(TKey));
        XmlSerializer value_serializer = new XmlSerializer(typeof(TValue));
    
        writer.WriteAttributeString("type", m_dictionary.GetType().AssemblyQualifiedName);
    
        foreach (TKey key in m_dictionary.Keys)
        {
          writer.WriteStartElement("item");
    
          writer.WriteStartElement("key");
          key_serializer.Serialize(writer, key);
          writer.WriteEndElement();
    
          writer.WriteStartElement("value");
          TValue value = m_dictionary[key];
          value_serializer.Serialize(writer, value);
          writer.WriteEndElement();
    
          writer.WriteEndElement();
        }
      }
    
      #endregion
    };
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

How to I serialize an object like this with protobuf-net: public class MyObject{ public
If i try to serialize an object of the following ClassToSerialize class with System.Runtime.Serialization.Json.DataContractJsonSerializer
When I try to serialize class with protected members, I get the following errors:
I'm getting the following error when I try to Serialize an HttpWebRequest Type 'System.Net.KnownHttpVerb'
Here's my code: [Serializable()] public class Project { private List<string> _Kinds = new List<string>();
Im trying the serialize the modelstate to an xml string. First I create a
I try to serialize to a binary archive then load this archive using the
I'm getting this error when I try to serialize a Method object. java.io.NotSerializableException: java.lang.reflect.Method
I want to serialize an object. I've got this basic class structure: class Controller
The situation is like this : Main project A. and a class library B.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.