Search code examples
c#asp.netserializationwebformsviewstate

How to Host Portable Class Library Class Instance in ViewState


I have an ASP.NET Web-forms application with two projects: The main Web project and a portable class library project. I have the following code:

In the portable project I have an Item class:

public class Item
{
    public int ID { get; set; }

    public string Name { get; set; }
}

And in the Default.aspx.cs page I have the following demo code:

protected void Page_Load(object sender, EventArgs e)
{
    Item item = new Item();
    item.ID = 1;
    item.Name = "John";
    ViewState["MyKey"] = item;
}

protected void Button1_Click(object sender, EventArgs e)
// Obviously I have a button named "Button1" on the page.
{
    if (ViewState["MyKey"] != null)
    {
        Item item = (Item)ViewState["MyKey"];
        Button1.Text = item.ID + " " + item.Name;
    }
}

Obviously that is causing the error:

Type 'PortableProject.Item' in Assembly 'PortableProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable

While I'm aware of the problem and the expected solution, I'm not able to implement it. The solution is to provide the attribute [Serializable] to the Item class. However, this is not possible because the portable class library does not have System.SerializableAttribute. I'm aware of this similar question. However, decorating the class with the [DataContract] attribute and the members with [DataMember] has not solved the problem (the same error kept showing). Apparently the view state serializes the object in a particular way that requires the functionality that the [Serializable] attribute provides. So, how to put an instance of Item in the View State without having the preceding error?

EDIT

I'm still looking for a solution. Obviously my portable project will be consumed by cross-platform environments, that's why I have to keep it a portable class library. Moreover, I wish to use the classes within that portable class library in my web forms pages (namely the ViewState object).

This search appeared to be so promising but I still couldn't get a hold of a workaround.


Solution

  • You can just use Json.Newtonsoft to convert the object into a string. Then use that string within the Viewstate.

    Something like this should work.

     Item item = new Item();
        item.ID = 1;
        item.Name = "John";
        ViewState["MyKey"] = JsonConvert.SerializeObject(item);