当用到.net 时,很多新手都为如何解决.cs文件里数组赋值给.aspx中js数组的问题。这次主要和大家分享怎么解决这个问题!
第一步:定义cs数组
cs代码:
using System.Data;
using System.Configuration;
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;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
public double[] la = new double[25]; //定义为公共数组
public double[] ln = new double[25];
public int[] id = new int[25];
public int k1 = 0; //定义为公共,用于赋值循环
protected void Page_Load(object sender, EventArgs e)
{
}
}
第二步:将cs数组赋值
string mycnnConnectionString1 = System.Configuration.ConfigurationManager.AppSettings["strcon"].ToString(); //创建连接字符串
SqlConnection mycnn1 = new SqlConnection(mycnnConnectionString1);
mycnn1.Open();
SqlCommand cmd1 = new SqlCommand("select id,lat,lng from station ", mycnn1);
SqlDataReader dr1 = cmd1.ExecuteReader();
int k2 = 0;
int k3 = 0;
int k4 = 0;
string buf1 = "";
double buf2 = 0;
double buf3 = 0;
int buf4 = 0;
while (dr1.Read())
{
//lat
buf2 = (double)dr1["lat"];
la[k2] = buf2;
k2++;
//lng
buf3 = (double)dr1["lng"];///数据库读取float型的数据要用double
ln[k3] = buf3;
k3++;
//id
buf4 = (int)dr1["id"];
id[k4] = buf4;
k4++;
}
第三步:将cs数组赋值个js数组
aspx代码:
.........
<script type="text/javascript">
//赋值的代码要写在这里<script type="text/javascript">代码...</script>
var jingdu= new Array();
var weidu=new Array();
var id=new Array();
<%
for(int i=0;i<25;i++){
%>
jingdu.push(<%=ln[i]%>);
weidu.push(<%=la[i]%>);
id.push(<%=id[i] %>);
<%
}
%>
</script>
通过这次的解决,我们发现js和前台后台的交互都是较为简单的传送,其实他还有很多封装好的方法,咱们下次研究,敬请期待