繁体   English   中英

将数据表从C#动态传递到Javascript

[英]Dynamically pass datatable from C# to Javascript

aspx.cs文件

通过使用C#从Excel文件中读取值,可以在运行时生成数据表。 如何将其传递给javascript?

protected void btnRead_Click(object sender, EventArgs e)
{
      Upload();  //Upload File Method
      DataTable dt = ReadExcelWithStream(currFilePath); 
    //on button click it reads file path of excel and stores it in a string path 
    //calls the ReadExcelWithStream Method to read the excel File
}

  private void Upload()
        {
            HttpPostedFile file = this.fileSelect.PostedFile;
            string fileName = file.FileName;
            string tempPath = System.IO.Path.GetTempPath();   //Get Temporary File Path
            fileName = System.IO.Path.GetFileName(fileName); //Get File Name (not including path)
            this.currFileExtension = System.IO.Path.GetExtension(fileName);   //Get File Extension
            this.currFilePath = tempPath + fileName; //Get File Path after Uploading and Record to Former Declared Global Variable
            file.SaveAs(this.currFilePath);  //Upload
        }
    private DataTable ReadExcelWithStream(string path)
    {
       bool isDtHasColumn = false;   //Mark if DataTable Generates Column
       StreamReader reader = new StreamReader(path, System.Text.Encoding.Default);  //Data Stream
       while (!reader.EndOfStream)
       {
       string message = reader.ReadLine();
       string[] splitResult = message.Split(new char[] { ',' }, StringSplitOptions.None);  //Read One Row and Separate by Comma, Save to Array
       DataRow row = dt.NewRow();
       for (int i = 0; i < splitResult.Length; i++)
            {
                if (!isDtHasColumn) //If not Generate Column
                {
                    dt.Columns.Add("column" + i, typeof(string));
                }
                row[i] = splitResult[i];
            }
       dt.Rows.Add(row); 
       isDtHasColumn = true;  //Mark the Existed Column after Read the First Row, Not Generate Column after Reading Later Rows
        }
        //method(here coding to read the excel file and stores it in a dt is written)
        ForJs(dt);
        return dt;
    }

[ScriptMethod, WebMethod]
public static DataTable ForJs(DataTable dt)
{
  return dt;
}

ASPX

<script type="text/javascript">
    function InsertLabelData() {
        PageMethods.ForJs(onSuccess, onFailure);
    }
    function onSuccess(dt) {
     //attach the table to dhtmlx grid
    }

但是数据表未传递给javascript。 如何将数据表从C#传递到JavaScript

您不能简单地将(y)对象传递给JavaScript。 它必须是可用的格式。 像数组或序列化为XML或JSON。 另外,“ DataTables包含许多JSON无法存储的其他信息 ”。

看一下如何将c#数据表传递给javascript函数,或者jSON在WCF中序列化.NET数据表的最佳方法是什么? 有关此主题的更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM