我正在尝试使用asp.net中的以下方法将远程数据加载到select2输入类型隐藏
public String ConvertDatasettoArrayList()
{
DataSet ds = new DataSet();
// List<UserDetails> details = new List<UserDetails>();
ArrayList list = new ArrayList();
SqlConnection con = new SqlConnection("server=PBSUSER5;database=graph;user id=sa;password=panacya");
SqlCommand cmd = new SqlCommand("usp_selecttables_info", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
StringBuilder sb = new StringBuilder();
sb.Append("[");
int i = ds.Tables[0].Rows.Count;
int j = 1;
foreach (DataRow dtrow in ds.Tables[0].Rows)
{
sb.Append("{id:" + Convert.ToInt32(dtrow["id"].ToString()) + ",text:");
sb.Append("'" + dtrow[1].ToString()+"'");
sb.Append("}");
if (i != j)
sb.Append(",");
j++;
list.Add(dtrow);
}
sb.Append("]");
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string s = sb.ToString();
return serializer.Serialize(s);
}
此方法返回字符串
[{id:1,text:'panacya'},{id:2,text:'items'},{id:3,text:'systems'},{id:4,text:'devlopment'},{id:5,text:'cellphones'},{id:6,text:'textfeels'}]
脚本是,当我静态绑定该字符串数组时它正在工作但是当绑定远程数据变量时它没有加载。
$(function () {
alert('calling');
var d =JSON.parse( '<%=ConvertDatasettoArrayList()%>');
alert(d)
$("#ex2").select2({
data: [{ id: 1, text: 'panacya' }, { id: 2, text: 'items' }, { id: 3, text: 'systems' }, { id: 4, text: 'devlopment' }, { id: 5, text: 'cellphones' }, { id: 6, text: 'textfeels' }]// working fine but for below statement
data: d// remote data variable it is not binding
});
});
</script>
答案 0 :(得分:0)
由于JSON-String已包含'
,因此在将数据放入String时,您必须转义它们或使用"
。使用以下代码设置d
:
var d=JSON.parse("<%=ConvertDatasettoArrayList()%>");