如何在 ViewState 中托管便携式 Class 库 Class 实例

How to Host Portable Class Library Class Instance in ViewState

我有一个包含两个项目的 ASP.NET Web 表单应用程序:主 Web 项目和一个 portable class library project。我有以下代码:

在便携式项目中我有一个 Item class:

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

    public string Name { get; set; }
}

在 Default.aspx.cs 页面中,我有以下演示代码:

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;
    }
}

显然这是导致错误的原因:

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

虽然我知道问题和预期的解决方案,但我无法实施。解决方案是将属性 [Serializable] 提供给 Item class。但是,这是不可能的,因为可移植 class 库没有 System.SerializableAttribute。我知道 this 类似的问题。但是,用 [DataContract] 属性修饰 class 并用 [DataMember] 修饰成员并没有解决问题(同样的错误不断出现)。显然,视图状态以需要 [Serializable] 属性提供的功能的特定方式序列化对象。那么,如何将Item的实例放入View State中而不出现前面的错误呢?

编辑

我仍在寻找解决方案。显然我的可移植项目将被跨平台环境使用,这就是为什么我必须将其保留为 可移植 class 库。此外,我希望在我的 Web 表单页面(即 ViewState 对象)中使用便携式 class 库中的 classes。

This 搜索似乎很有希望,但我仍然无法找到解决方法。

您可以只使用Json.Newtonsoft 将对象转换为字符串。然后在 Viewstate 中使用该字符串。

像这样的东西应该有用。

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