Search code examples
javascriptasp.netviewstate

JavaScript getting custom object from viewstate


I am pretty sure this question would have been asked before but I cannot find it so please post the link to where I can go to it if so..

However, I persist some data on a Postback in asp.net using a ViewState. The ViewState contains a collection of my own custom object. e.g.

 ViewState["List"] as List<Animal>

Is it possible I can get this list and pass it to the client-side? so really, can it be serialised?

I have tried:

// HTML
<asp:TextBox ID="theList" runat="server" style="display:none"></asp:TextBox> 

 //Sever Side
theList.Text = ViewState["List"].Tostring();

//JS
document.getElementById('theList').innerText;

but of course, this isn't my data this contains the namespace.

My first thoughts was to use JSON.Parse on the client, however I need to pass the data first which is the main issue.

Thanks


Solution

  • user3428422 has it right (he/she beat me to the post). You might also consider:

        public List<Animal> AnimalList
        {
            get
            {
                if (!(ViewState["lAnimalList"] is List<Animal>))
                {
                    ViewState["lAnimalList"] = new List<Animal>();
                }
                return (List<Animal>)ViewState["lAnimalList"];
            }
        }
    

    and then in your Page_Load event have:

            JavaScriptSerializer jss = new JavaScriptSerializer();
            HiddenField.Value = jss.Serialize(AnimalList);
    

    Its the same idea though. You should reward user3428422 first and foremost.