on MyPage.aspx.cs I have List of object
protected List<MyObj> myObjList =null;
protected void Page_Load(object sender, EventArgs e)
{
myObjList = GetObjByUserId("23423");
}
on aspx page I want to assign this list of objects to JS variable
<script type="text/javascript">
$(document).ready(function () {
var BookingsList = <%=myObjList %>;
</script>
but is assign type like string=>
System.Collections.Generic.List`1[myObj]
how I can to assign my collection of object from CS to JS variable?
on MyPage.aspx.cs I have List of object
protected List<MyObj> myObjList =null;
protected void Page_Load(object sender, EventArgs e)
{
myObjList = GetObjByUserId("23423");
}
on aspx page I want to assign this list of objects to JS variable
<script type="text/javascript">
$(document).ready(function () {
var BookingsList = <%=myObjList %>;
</script>
but is assign type like string=>
System.Collections.Generic.List`1[myObj]
how I can to assign my collection of object from CS to JS variable?
Share Improve this question asked Oct 24, 2014 at 12:29 AlexAlex 9,74030 gold badges107 silver badges166 bronze badges 02 Answers
Reset to default 2Try using JavaScriptSerializer like following:
c# Code
Student student = new Student();
System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string StudentJson = oSerializer.Serialize(resources);
and in your aspx code get it like:
<script type="text/javascript">
var jsonStudent = <%=StudentJson%>;
</script>
Please make sure that StudentJson is a public or protected property in your backend class
You need to put the list in javascript format. In pure javascript you are looking for the following output (as an example):
var jsList = ['val1', 'val2', 'val3'];
To get this from .NET you need to use the Join
function to bine list items into the appropriate format. The plete line of code looks like:
var jsList = <%= "['" + string.Join("', '", myObjList.ToArray()) + "']" %>;
Note that this assumes your "ToString" on your elements generates the output you are looking for and does not include single quotes. Hope that helps!