ASP.NET - save in view mode without serialization

I am trying to save a complex object in Viewstate so as not to name it every time the page loads. I understand that it must be serialized in order to save and retrieve from ViewState, which means that my class should be marked as[Serializable]

This is a rather complex entity, and basically I want to avoid marking each class as Serializable, as this may affect my other dependencies used for matching.

Class Article
{
    Albums albumList { get; set; }
    Authors authorList { get; set; }
    ...
}

Is this possible and is there any possible way out to save and retrieve the ViewState without serialization?

+5
source share
4 answers

, , " " . , , , , , , ( ).

json.net, . viewstate, , . ( ) - , .

, , , , .

, , , JSON.net( ):

//Doesnt need to be marked as serializable
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[] { "Small" };
//Use this string to save into view state
string json = JsonConvert.SerializeObject(product);
ViewState["something"]=json;

ViewState [something] .

string json = (string)ViewState["something"];
Product m = JsonConvert.DeserializeObject<Product>(json);

, .

+2

ASP.NET Session ( , Session Object), :

var theArticle = new Article();

Session["MyArticle"] = theArticle;

Session , , Article, Article, :

var myArticleFromSession = Session["MyArticle"] as Article;

. , Session, , :

if(Session["MyArticle"] != null)
{
    // The key MyArticle exists, so it is safe to attempt to get the object value
    var myArticleFromSession = Session["MyArticle"] as Article;

    // Since we used as to attempt the cast, 
    // then myArticleFromSession will be null if the cast failed 
    // so check for null before using myArticleFromSession
    if(myArticleFromSession != null)
    {
        // Use myArticleFromSession here

    }
}
+1

, , ( ).

postbacks , ASP.NET Session , Application System.Web.Caching.Cache . ASP.NET . : ASP.NET

, . BasePage. , , . :

0

- [NonSerialized] . .

, , ,

[Serializable]
Class Article
{
    Albums albumList { get; set; }

    [NonSerialized]
    Authors authorList { get; set; }
    ...
}
0

Source: https://habr.com/ru/post/1616539/


All Articles