我使用 ajax 控件为 div 加载和动态创建 id。所以它不起作用。因为 ajax 控件将在 javascript 加载后加载。
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Eventcalander.aspx/BindDatatable",
data: "{}",
dataType: "json",
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
$("#gvEventDetails").append("<tr><td><div width:32px; height:32px; id= drag" + i + " class=\"dragg\" style= background-color:" + data.d[i].Color + ">" + data.d[i].EventID + "</div></td></tr>");
}
},
error: function (result) {
alert("Error");
}
});
在代码隐藏中我这样使用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;
namespace DragDropDynamically
{
public partial class Eventcalander : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindColumnToGridview();
}
}
/// <summary>
/// This method is used to bind dummy row to gridview to bind data using JQuery
/// </summary>
private void BindColumnToGridview()
{
DataTable dt = new DataTable();
dt.Columns.Add("EventID");
dt.Rows.Add();
gvEventDetails.DataSource = dt;
gvEventDetails.DataBind();
gvEventDetails.Rows[0].Visible = false;
}
[WebMethod]
public static EventDetails[] BindDatatable()
{
DataTable dt = new DataTable();
List<EventDetails> lstEventdetails = new List<EventDetails>();
using (SqlConnection con = new SqlConnection("Server=CTSINDLFVMOSS;Database=databasename;uid=userid;pwd=password"))
{
using (SqlCommand cmd = new SqlCommand("SELECT TOP 1000 [EventID],[EventStartDate],[EventEndDate],[EventPeriod],[Feature],[Display],[FeatureandDisplay],[TPR],[Color] FROM [DB_CGTPO_DEVE].[dbo].[HistoryEvent]", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dtrow in dt.Rows)
{
eventdetails.EventID = dtrow["EventID"].ToString();
eventdetails.Color = dtrow["Color"].ToString().Trim();
lstEventdetails.Add(eventdetails);
}
}
}
return lstEventdetails.ToArray();
}
public class EventDetails
{
public string EventID { get; set; }
public string Color { get; set; }
}
}
}