Fill javascript array with C# in ASP.NET.

This is a very simple code snippet in ASP.NET. In this article, I will show you how to fill JavaScript Array from C# code behind and then read the value of the Array on the client-side and display it to the page. ASP.NET WebForm provides A API, RegisterArrayDeclarationThat takes the value from C# and add it to the page as a JavaScript array.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ClientSideCalcGridview.aspx.cs"
   Inherits="ClientSideCalcGridview" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <input type="text" id="indexText" />
           <input type="button" id="showButton"
 value="Show Array Element By Index"
onclick="ShowItem(document.getElementById('indexText').value);" />
       </div>
   </form>
</body>

<script type="text/javascript">
       function ShowItem(index)
       {
          alert('myArray['+index+'] = ' + myArray[index]);
         //alert(myArray[index]); 
       }
</script>

</html>

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class ClientSideCalcGridview : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
       Session.Clear();
       DataSet ds = new DataSet();
       if (Session["dt"] == null)
       {
           ds = c();
       }
       else
       {
           ds = Session["dt"] as DataSet;
       }
       foreach (DataRow dr in ds.Tables[0].Rows)
       {
           this.ClientScript.RegisterArrayDeclaration("myArray", "'" + dr["Address"].ToString() + "'");

       }
   }
   public DataSet c()
   {
       DataSet ds = new DataSet();
       DataTable dt = new DataTable("Company");
       DataRow dr;
       dt.Columns.Add(new DataColumn("accountNo", typeof(Int32)));
       dt.Columns.Add(new DataColumn("CompanyName", typeof(string)));
       dt.Columns.Add(new DataColumn("Address", typeof(string)));
       for (int i = 0; i <= 10; i++)
       {
           dr = dt.NewRow();
           dr[0] = i;
           dr[1] = "Company" + i + Environment.NewLine + "Title" + i;
           dr[2] = "Address" + i.ToString();
           dt.Rows.Add(dr);
       }
       ds.Tables.Add(dt);
       Session["dt"] = dt;
       return ds;
   }
}

Please do not post any spam link in the comment box😊

إرسال تعليق (0)
أحدث أقدم