0

I have a DataTable object in C#, I pass the object to my aspx class in JavaScript like below. In JavaScript, I have a loop over the pages of a PowerBI report. All I need to do is to compare if the PageLists (from c#) includes page.DisplayName and do some process based on that. See the code below:

C#:

DataTable PagesList = null; //(this is globally defined)
...
protected void Page_Load(object sender, EventArgs e)
{
   PagesList = sql.QueryDataTable(String.Format("select PageLabel, DefaultPage from myTable where ReportID = '{0}';",ReportID));
}

JavaScript:

<script>
   var pageslist = "<%=PagesList%>";
   alert(pageslist); //This pops up: "Table"

   report.getPages().then(function (pages) {  
        var allpages = ''
        pages.forEach(function(page) { 
            if(pageslist.includes(page.displayName) > -1) //this is not working properly
            {  
               allpages = allpages+'<button type="button" onclick=setPage(\''+page.name+'\')>'  + page.displayName+'</button>';
            }
        });
        ...
        ...

Here, it is not working as I expected, if part always returns false. What is the best way for this case to check if pageslist include page.displayName or not? How can I receive the items of the pageslist? Any help would be appreciated.

Eray Balkanli
  • 7,752
  • 11
  • 48
  • 82
  • You cannot loop the contents of a C# DataTable like that. You need to serialize it as json, xml etc and send it to the front-end where it can be read by javascript. – VDWWD Jan 15 '19 at 15:40
  • As @VDWWD said, you will probably want to serialize your DataTable to JSON. See Newtonsoft: https://www.newtonsoft.com/json/help/html/SerializeDataSet.htm and this post: https://stackoverflow.com/q/17398019/1617161 – iCode Jan 15 '19 at 15:47
  • Also, .includes() returns a boolean, so your condition of > -1 is always true. See .includes() docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes – iCode Jan 15 '19 at 15:49
  • Tried IndexOf as well. Working on DataTable to Json now. – Eray Balkanli Jan 15 '19 at 15:51

1 Answers1

0

You are using includes which return true or false so you dont need this part : > -1. You can change your condition :

 if(pageslist.includes(page.displayName)) 

or you can use indexOf :

 if(pageslist.indexOf(page.displayName) > -1) 
Emad Dehnavi
  • 3,262
  • 4
  • 19
  • 44