Pass IEnumerable List to javascript

后端 未结 2 1628
离开以前
离开以前 2021-01-14 04:48

I was wondering if I could pass a IEnumerable Collection into a Javascript method on the page load. So something like this...

<%@ Control Language=\"C#\"          


        
2条回答
  •  臣服心动
    2021-01-14 05:17

    You can register the javascript in the code behind in the Page_Load with the following code (Note I am assuming that Model.NewsList is a string enumeration or array):

    StringBuilder sb = new StringBuilder();
    bool isFirst = true;
    //build a comma seperated list.
    foreach (string s in Model.NewsList)
    {
        if (isFirst)
            isFirst = false;
        else
            sb.Append(", ");
        sb.Append("'").Append(s.Replace("'", "''")).Append("'");
    }
    //create the javascript array
    string javascript = String.Format(@"var news = [{0}];", sb);
    //put the array in the generated page.
    Page.ClientScript.RegisterClientScriptBlock(GetType(), "newsList", javascript);
    

    This will put the javascript on the page accessible from other javascript functions.

提交回复
热议问题