如何在jquery中绑定asp DataList?

时间:2015-09-11 13:00:40

标签: c# asp.net json

我从sql获取数据并且可以在json处成功返回和检索但是无法绑定到下面的DataList控件。

<asp:DataList ID="dlImages" runat="server" RepeatColumns="6">
<ItemTemplate>
<a id="imageLink" href='<%# Eval("ImageName","~/images/fabrics/{0}") %>' title='<%#Eval("Descript") %>' rel="lightbox[Brussels]" runat="server" >
<asp:Image ID="Image1" ImageUrl='<%# Bind("ImageName", "~/images/fabrics/{0}") %>' runat="server" Width="100px" Height="60px" hspace="20px"/><br />
<asp:Label ID="lbl1" runat="server" Text='<%#Eval("ImageAssignedName") %>'  Height="30px"></asp:Label>
</a> 
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Bottom"/>
</asp:DataList>

/ Jquery部分 /

<script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "WebForm2.aspx/BindDatatable",
                data: "{}",
                dataType: "json",
                success: function (data) {
                    alert(data.d);

//在此警报中获取[对象对象] .... [对象对象]

for (var i = 0; i < data.d.length; i++) {
                        alert('Hello')   


                       //till here i can come


 var row = $("#imageLink").html(data.d[i].ImageName);
                        row = $("#Image1").html(data.d[i].ImageName);
                        row =  $("#lbl1").html(data.d[i].ImageAssignedName);
                        $("[id*=dlImages]").append(row); 

这是我不能绑定

 }   



            },
            error: function (result) {
                alert("Error");
            }
        });
    });

/ C#webmethode代码 /

[WebMethod]
        public static UserDetails[] BindDatatable()
        {
            DataTable dt = new DataTable();
            List<UserDetails> details = new List<UserDetails>();

            using (SqlConnection connnection = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString.ToString()))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT Fabrics.ImageName,Fabrics.Descript,ImageAssignedName from Fabrics", connnection))
                {
                    connnection.Open();
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    da.Fill(dt);
                    foreach (DataRow dtrow in dt.Rows)
                    {
                        UserDetails user = new UserDetails();
                        user.ImageName = dtrow["ImageName"].ToString();
                        user.Descript = dtrow["Descript"].ToString();
                        user.ImageAssignedName = dtrow["ImageAssignedName"].ToString();
                        details.Add(user);
                    }
                }
            }
            return details.ToArray();
        }
        public class UserDetails
        {
            public string ImageName { get; set; }
            public string Descript { get; set; }
            public string ImageAssignedName { get; set; }
        }

1 个答案:

答案 0 :(得分:0)

首先,您是否正确地从WebMethod返回JSON?让我们确定一下

using System.Web.Script.Serialization; //this is needed for some classes

[DataContract] //these attributes hel the serializer to serialize the object
internal class UserDetails
{
    [DataMember]
    public string ImageName { get; set; }
    [DataMember]
    public string Descript { get; set; }
    [DataMember]
    public string ImageAssignedName { get; set; }
}

protected static IEnumerable<UserDetails> GetFabrics()
{
    var details = new List<UserDetails>();

    using (var connnection = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString.ToString()))
    using (var cmd = new SqlCommand("SELECT Fabrics.ImageName,Fabrics.Descript,ImageAssignedName from Fabrics", connnection))
    {
        var reader = cmd.ExecuteReader();

        while(reader.Read())
        {
            yield return new UserDetails
            {
                ImageName = reader.GetString(0),
                Descript = reader.GetString(0),
                ImageAssignedName = reader.GetString(0),
            };
        }
    }
}

[WebMethod]
public static string BindDataGrid()
{
    var result = GetFabrics(); //this is a IEnumerable<UserDetails>, 

    var jsonSerialiser = new JavaScriptSerializer();
    var json = jsonSerialiser.Serialize(result); //this does everyting

    return json;
}

然后在html中

$(function(){
    $.ajax({
        //bla
        success: function(data){
            alert(data); //this should show "[{ ImageName: "foo" ... }] etc
            var dataset = JSON.parse(data);
            for(var in in dataset){
                $('#dlImages').append('<tr><td>' + dataset[i].ImageName + '</td></tr>');
            }
        }
    }
});

问题是你为什么不在这个服务器端做这个?

protected override void Page_Load(object sender, EventArgs e)
{
    dlImages.DataSource = GetFabrics();
    dlImages.DataBind(); //Done!
}