c# - 从codebehind添加javascript函数

时间:2018-06-12 04:11:08

标签: javascript c# jquery asp.net webforms

DBDataSet.tblAdsDataTable dtAds = client.getAdsDate(ref errCode, AdsType, AdsSlot, Country);
        string ss = "";
        string aa = "";
        if (dtAds.Rows.Count > 0)
        {
            foreach (DBDataSet.tblAdsRow dr in dtAds)
            {
                DateTime date = dr.AdsDate;
                string AdsDate = date.ToString("dd/MM/yyyy");

                ss += '"' + AdsDate + '"' +",";  
                aa = ss.TrimEnd(','); // equal to "01/01/2018","02/01/2018"

                string jquery = "var naArray = ["+ aa +"];";;
                ClientScript.RegisterStartupScript(typeof(Page), "a key","<script>" + jquery + "</script>");
            }
        }

嗨,从上面的代码中,我想在代码中添加javascript,如<script> var naArray = ["01/01/2018","02/01/2018"];</script>。但是,当我执行时,它变为<script> var naArray = ["01/01/2018"]; <script>数组中缺少“02/01/2018”。感谢是否有人可以提供帮助。感谢。

2 个答案:

答案 0 :(得分:1)

你正在将值设置为jquery变量在foreach循环中。它应该在循环之外。尝试更新您的代码,如下所示。

DBDataSet.tblAdsDataTable dtAds = client.getAdsDate(ref errCode, AdsType, AdsSlot, Country);
string ss = "";
string aa = "";
if (dtAds.Rows.Count > 0)
{
    foreach (DBDataSet.tblAdsRow dr in dtAds)
    {
        DateTime date = dr.AdsDate;
        string AdsDate = date.ToString("dd/MM/yyyy");

        ss += '"' + AdsDate + '"' +",";                  
    }
    aa = ss.TrimEnd(','); // equal to "01/01/2018","02/01/2018"
    string jquery = "var naArray = ["+ aa +"];";;
    ClientScript.RegisterStartupScript(typeof(Page), "a key","<script>" + jquery + "</script>");
}

答案 1 :(得分:0)

        string aa = "";

        foreach (DBDataSet.tblAdsRow dr in dtAds)
        {
            DateTime date = dr.AdsDate;
            string AdsDate = date.ToString("dd/MM/yyyy");

            aa += '"' + AdsDate + '"' + ","; // equal to "01/01/2018","02/01/2018"
        }

        aa = aa.TrimEnd(',');

在循环外部附加javascript。您的值在每次迭代中都在变化。