asp.net如何將後台c#數組傳給前台js?

來源:互聯網
上載者:User

 如何把背景c#數組傳給前端的js,所以這個問題困擾了很久,後來在一篇文章中看到解決辦法,文章中的方法處理的是定長數組,我現在處理的是不定長的,所以我又在文章的基礎上修改了一下。自己親自的實踐了一下並應用在自己的程式中,果然解決了問題。現在結合大牛的文章和我自己的親身實踐來說明一下這個問題是如何解決的。

  

第一步:定義cs數組

cs檔案裡背景程式中要有數組,這個數組要定義成公用的數組。

public string[] lat = null;

public string[] lng = null;

第二步:給cs數組賦值

cs數組的值一般都是從資料庫中取到的,相信大家也都會,且後邊的代碼中也會有描寫,這裡就不做詳細的解釋。

第三步:將cs數組賦給前端的js數組

這個步驟是關鍵,我選用的方法就是<%=cs數組%>。這樣模糊的說法也是百度得到的,賦值會用到迴圈,即會一個元素一個元素的賦值。

後台cs代碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Data;
using System.Collections;

public partial class VideoSource : System.Web.UI.Page
{
    public string[] lat = null;//存放緯度值
    public string[] lng = null;//存放經度值
    public int lng_len = 0;//用於獲得數組長度
    public int k = 0;//用於賦值迴圈
    protected void Page_Load(object sender, EventArgs e)
    {
       ArrayList lng_list = new ArrayList();
       ArrayList lat_list = new ArrayList();
        OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath("App_Data/Database1.accdb"));
        con.Open();
        string sql = "select * from tb_videos";
        try
        {
            OleDbDataAdapter gh = new OleDbDataAdapter(sql, con);
            DataSet ds = new DataSet();
            gh.Fill(ds);
            con.Close();
            foreach (DataRow DR in ds.Tables[0].Rows)
            {
                lng_list.Add(DR[2].ToString());
                lat_list.Add(DR[3].ToString());
            }
        }
        catch
        {
            con.Dispose();
        }
        lng = (string[])lng_list.ToArray(typeof(string));
        lat = (string[])lat_list.ToArray(typeof(string));
        lng_len = lng_list.Count;
    }


aspx代碼

<script type="text/javascript">
        var jingdu = new Array();
        var weidu = new Array();
        <%
        for(int k=0;k<lng_len;k++){
         %>
         jingdu.push("<%=lng[k]%>");
         weidu.push("<%=lat[k]%>");
        <%
        }
         %>
         var latlng=[];
         for(var i=0;i<jingdu.length;i++){
         latlng.push(new google.maps.LatLng(jingdu[i],weidu[i]));
         }
</script>

 

上述代碼即為我解決問題所用代碼,均已實驗通過。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.