havin havin - 3 months ago 58
ASP.NET (C#) Question

Bind Dataset to ASP.Net Div tag using jQuery AJAX

Iam Binding <%#Eval("message") %> inside Div tag.Now iam fetching data from db using dataset inside repeater .Each time page is loading fetching data from db which i want to avoid.So i decided to use Jquery ajax to bind dataset.My problem is how can we bind dataset inside div tag.

My code is :

<asp:Repeater ID="rep" runat="server"
OnItemDataBound="rep_ItemDataBound"> <ItemTemplate>
<div>
<p><%#Eval("message") %></p>
</div>
</ItemTemplate>
</asp:Repeater>


Code Behind:

[WebMethod]
public static string GetMessages()
{
string query = "GetMessageData";
SqlCommand cmd = new SqlCommand(query);
cmd.CommandType = CommandType.StoredProcedure;
return GetData(cmd).GetXml();
}
private static DataSet GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["connectionng"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;

}
}
}
}


Javascript:

$(function () {
$.ajax
({
type: "POST",
url: "welcome.aspx/GetMessages",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
});

function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
--Iam stuck Here--


}

So if success how can i bind my dataset to div tag inside repeater.

Answer

All you really have to do is loop through the XML returned by the $.ajax call and append the results to an element on the page.

1.Add <div id="result"></div> anywhere on your page.We will write the output of the $.ajax call to this element.

2.Change your OnSuccess() function like this:

function OnSuccess(response) {
    var xmlDoc = $.parseXML(response.d);
    var length = xmlDoc.children[0].children.length;
    $("#result").empty();

    for(var i = 0; i < length; i++)
    {
        var item = xmlDoc.children[0].children[i];
        var message = item.getElementsByTagName("message")[0].innerHTML;
        var div = "<div><p>" + message + "</p></div>";
        $("#result").append(div);
    }
}
Comments