2

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"];
10
  • Create a webmethod which contain your code behind logic and call it using ajax. Commented Nov 20, 2016 at 3:06
  • or print serialized json into page as value of the variable. Both approaches are very easy to research Commented Nov 20, 2016 at 4:01
  • @Div I tried, but I kept getting something like [Object] object or \Date(random numbers)/ Commented Nov 20, 2016 at 5:08
  • @Arane: Add that code in the question. Commented Nov 20, 2016 at 5:25
  • 1
    @Div Managed to do it, at long last haha... thank you so much for the guidance and help! Much appreciated!! Commented Nov 20, 2016 at 6:07

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Merci Beaucoup!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.