0

i'm developing a .net application using twitter bootstrap.

I'm trying to get data from .aspx.cs page to .aspx page.

Please find my code below:

strOblect.cs

public class strObject
{
 public string Name { get; set; }
 public string Description { get; set; }
}

.aspx.cs page:

public List<strObject> stringList = new List<strObject>();
protected void Page_Load(object sender, EventArgs e)
{
   strObject ObjOne=new strObject();
   ObjOne.Name="One";
   ObjOne.Description ="One";
   stringList.Add(ObjOne);
   strObject ObjTwo=new strObject();
   ObjTwo.Name="Two";
   ObjTwo.Description ="Two";
   stringList.Add(ObjTwo);
   strObject ObjThree=new strObject();
   ObjThree.Name="Three";
   ObjThree.Description ="Three";
   stringList.Add(ObjThree);
}

.aspx:

<asp:Panel  ID="pnlData"  runat="server" style="background-color:White;">

<script type="text/javascript">

 $(document).ready(function () {
    var valueAssigned=stringList;
});

</script>

</asp:Panel>

I'm unable to get stringList value in $(document).ready.

Please help me out to get the value.

Prathiba
  • 45
  • 7

2 Answers2

4

It appears that your stringList is actually a collection of objects. In order to use it in JavaScript as such, you'll need to serialize it to a javascript object.

var valueAssigned=<%=new JavaScriptSerializer().Serialize(stringList)%>;

So that you can wind up with the following:

var valueAssigned= [{Name: "Foo", Description: "Bar"}, {...}];

Edit

JavaScriptSerializer is in System.Web.Script.Serialization - you'll either need to add this below at the top of your <%@ Page

<%@ Import Namespace="System.Web.Script.Serialization" %>

or specify the FQ name

var valueAssigned=<%=new System.Web.Script.Serialization.JavaScriptSerializer()
                         .Serialize(stringList)%>;
StuartLC
  • 104,537
  • 17
  • 209
  • 285
  • I got the error: **An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.** when i use var valueAssigned=<%=new JavaScriptSerializer().Serialize(stringList);%>; – Prathiba Dec 24 '14 at 09:17
  • Scuse the delay - you'll need to qualify the namespace. – StuartLC Dec 24 '14 at 15:21
1

StuartLC's answer will be enough.JSON is very good option for that purpose. Other option can be to register client script in aspx.cs. Here is another SO question regarding that

How do I pass data from c# to jquery/javascript?

Community
  • 1
  • 1
husnain_sys
  • 571
  • 4
  • 14