Arane Arane - 17 days ago 7
ASP.NET (C#) Question

Pass list of values from Code-Behind to Javascript

I currently have a

list
of dates in my code-behind, I'd like to pass the
list
to a variable in
javascript
without the use of
hiddenfield


For instance,

Aspx.cs:

List < DateTime > blockedDate = new List < DateTime > ();

foreach(DataRow blockedRow in phBLL.getAllPH(DateTime.Now.Year).Tables[0].Rows)
{
blockedDate.Add(Convert.ToDateTime(blockedRow["date1"]));
}


Aspx:

$(document).ready(function () {

var arrayOfDates = ""
});


What I've tried

Aspx.cs:

public static List < DateTime > blockedDate = new List < DateTime > ();

[WebMethod]
public static List < DateTime > blockDates()
{
foreach(DataRow blockedRow in phBLL.getAllPH(DateTime.Now.Year).Tables[0].Rows) {
blockedDate.Add(Convert.ToDateTime(blockedRow["date1"]));
}

return blockedDate;
}


Javascript:

$.ajax({
type: "POST",
url: "CreateClass.aspx/blockDates",
data: null,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function(result) {
for (var i = 0; i < result.d.length; i++) {
var dates = [new Date(parseInt(result.d[i].substr(6)))];
console.log(dates);
}
}
});


I am trying to get the
result
and place into an Array. So it'd end up something like this,

an array of dates

var array = ["2016/11/14", "2016/11/15", "2016/11/16"];

Div Div
Answer

As per comments, Create a [WebMethod] which contain your code behind logic and call it using ajax.

Now, you will get data on ajax success, and just push your data to array arrayOfDates using JavaScript Array push() Method

Hope this helps!