Not able to implement pagination in JQGRID using ASP.NET - asp.net

I have implemented a simple code to bind data to jqgrid in asp.net, I initially had problem with sorting the grid but was able to overcome the same. Now my concern is I am not able to implement pagination in Jqgrid. It would be great if anybody can help me out with this. Here is my aspx code.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%# Import Namespace="System.Web.Script.Serialization" %>
<%# Import Namespace="System.Collections.Generic" %>
<%# Import Namespace="System.Web.Services" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="ui.jqgrid.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
<%--<link href="jquery-ui-1.8.2.custom.css" rel="stylesheet" type="text/css" />--%>
<script src="grid.locale-en.js" type="text/javascript"></script>
<script src="jquery.jqGrid.min.js" type="text/javascript"></script>
<script src="json2.js" type="text/javascript"></script>
<link href="jquery-ui-1.8.7.custom.css" media="screen" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function() {
$('#list').jqGrid({
datatype: function(postdata) {
var params = new Object();
params.page = postdata.page;
params.pageSize = postdata.rows;
params.sortIndex = postdata.sidx;
params.sortDirection = postdata.sord;
$.ajax({
url: 'Default.aspx/GetData',
type: 'POST',
data: JSON.stringify(params),
// dataType: "json",
contentType: "application/json; charset=utf-8",
error: function(data, textStatus) {
alert('Error loading json');
},
success: function(data, st) {
if (st == 'success') {
var grid = $("#list");
var gridData = JSON.parse(data.d);
grid.clearGridData();
for (var i = 0; i < gridData.length; i++) {
grid.addRowData(i + 1, gridData[i]);
}
}
}
});
},
colNames: ['Product ID', 'Product Name', 'Product Number'],
colModel: [
{ name: 'ProductID', index: 'ProductID', sort: true, width: 80, align: 'center', sorttype: "int" },
{ name: 'Name', index: 'Name', width: 120, align: 'center' },
{ name: 'ProductNumber', index: 'ProductNumber', width: 120, align: 'center'}],
pager: $("#pager"),
height: 200,
width: 600,
rowNum: 20,
rowList: [10, 20, 30],
rownumWidth: 40,
sortorder: 'desc',
loadonce: true,
records: 20,
viewRecords: true
});
});
});
// }).navGrid('#pager', { search: true, edit: false, add: false, del: false, searchtext: "Search" });
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server">
</asp:ScriptManager>
<input type="button" id="submit" value="Fetch" title="Fetch" />
<table id="list">
</table>
<div id="pager">
</div>
</form>
</body>
</html>
And this is my code behind page
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;
using System.Collections.Generic;
using System.Text;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string GetData(int page, int pageSize, string sortIndex, string sortDirection)
{
string connectionString = GetConnectionString();
string queryString = string.Empty;
if (sortIndex == "")
{
queryString = "SELECT top " + pageSize + " ProductID,Name,ProductNumber FROM [AdventureWorks].[Production].[Product]";
}
else
{
queryString = "SELECT top " + pageSize + " ProductID,Name,ProductNumber FROM [AdventureWorks].[Production].[Product] ORDER BY " + sortIndex + " " + sortDirection;
}
DataSet ds = new DataSet();
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand command = connection.CreateCommand();
command.CommandText = queryString;
SqlDataAdapter da = new SqlDataAdapter(queryString, connectionString);
da.Fill(ds, "product");
DataTable dt = ds.Tables["product"];
IList<Product> pd = new List<Product>();
connection.Close();
for (int i = 0; i < dt.Rows.Count; i++)
{
Product p = new Product();
p.ProductID = dt.Rows[i]["ProductID"].ToString();
p.Name = Convert.ToString(dt.Rows[i]["Name"]);
p.ProductNumber = Convert.ToString(dt.Rows[i]["ProductNumber"]);
pd.Add(p);
p = null;
}
JavaScriptSerializer jsonSerz = new JavaScriptSerializer();
string serializedData = jsonSerz.Serialize(pd);
pd = null;
return serializedData;
}
static private string GetConnectionString()
{
return "Data Source=INMDCD0109\\SQLEXPRESS;Initial Catalog=AdventureWorks;Integrated Security=SSPI";
}
}
public class Product
{
public string ProductID { get; set; }
public string Name { get; set; }
public string ProductNumber { get; set; }
}
Thanks in advance

I wrote you already in the previous my answer many suggestion how to improve your code. Because you don't write any comment to my previous answer I will be short now.
I you need implement pagination, it is enough to use statement like SELECT TOP 10 only for the first page from 10 rows. If you need to return for example the 6-th page you need skip 50 first rows and then get the next 10. If the data which you return contain the id (ProductID in your case) you can do this for example with the following statement using common table expression (CTE):
WITH Previous (ProductID,Name,ProductNumber) AS (
SELECT TOP 50 ProductID,Name,ProductNumber
FROM [AdventureWorks].[Production].[Product]
)
SELECT TOP 10 T.ProductID,T.Name,T.ProductNumber
FROM [AdventureWorks].[Production].[Product] AS T
LEFT OUTER JOIN Previous AS P ON T.ProductID=P.ProductID
WHERE P.ProductID IS NULL
If the returned data contain no id, then you can use ROW_NUMBER to implement pagination.
UPDATED: One more small remark. The usage of DataSet, DataTable and SqlDataAdapter in your example is not effective. The usage of command.ExecuteReader (SqlCommand::ExecuteReader) which returns SqlDataReader seems me better here.

Related

How to show Arabic style in Google charts

<%# Page Language="C#" AutoEventWireup="true" CodeFile="Ar_PieChart.aspx.cs" Inherits="Ar_PieChart" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<meta http-equiv='content-type' content='text/html; charset=UTF-16' />
<meta name="viewport" content="width=device-height,minimum-scale=0.5,maximum-scale=3.0,user-scalable=yes" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="//www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', { packages: ['corechart'] });
</script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: 'Ar_PieChart.aspx/GetData',
data: '{}',
success:
function (response) {
drawVisualization(response.d);
}
});
})
function drawVisualization(dataValues) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Column Name');
data.addColumn('number', 'Column Value');
for (var i = 0; i < dataValues.length; i++) {
data.addRow([dataValues[i].ColumnName, dataValues[i].Value]);
}
new google.visualization.PieChart(document.getElementById('visualization')).draw(data, { is3D: true });
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="visualization" style="width: 600px; height: 350px">
</div>
</form>
</body>
</html>
Code Behind:
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.Web.Services;
using MySql.Data.MySqlClient;
public partial class Ar_PieChart : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static List<Data> GetData()
{
MySqlConnection conn = new MySqlConnection("server=****;user id=****;Password=****;database=****");
DataSet ds = new DataSet();
DataTable dt = new DataTable();
conn.Open();
string cmdstr = "SELECT Class,COUNT(Class) FROM sh_report GROUP BY Class";
MySqlCommand cmd = new MySqlCommand(cmdstr, conn);
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
adp.Fill(ds);
dt = ds.Tables[0];
List<Data> dataList = new List<Data>();
string cat = "";
int val = 0;
foreach (DataRow dr in dt.Rows)
{
cat = dr[0].ToString();
val = Convert.ToInt32(dr[1]);
dataList.Add(new Data(cat, val));
}
return dataList;
}
}
public class Data
{
public string ColumnName = "";
public int Value = 0;
public Data(string columnName, int value)
{
ColumnName = columnName;
Value = value;
}
}
I am getting chart perfectly but i am in need of Arabic style like reverse.
i mean while seeing the chart view in mirror.
If any one know the answer please help me.
Thanks in advance.

Fail to initiate connection in Signal R in asp.net

Below is my .aspx page code
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<link href="chat.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.6.4.js" type="text/javascript"></script>
<script src="Scripts/json2.js" type="text/javascript"></script>
<script src="Scripts/jquery.signalR-1.0.0-rc2.min.js" type="text/javascript"></script>
<script src="signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var query = window.location.search;
var toRemove = '?id=';
var gorge = query.replace(toRemove, '');
// Proxy created on the fly
var hub = $.connection.chatHub;
$.connection.hub.qs = "Id=" + gorge;
// Start the connection
$.connection.hub.start(function () {
//chat.server.getAllOnlineStatus();
});
});
</script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div id="container" class="wrap">
<div id="chatbox" class="chatbox">
<ul id="frndcontact">
</ul>
</div>
</div>
</form>
</body>
</html>
Below is my Hub class
[HubName("chatHub2")]
public class Chat2 : Hub
{
private SqlConnection objconn;
string Connstr = #"Data Source=somevalue;Initial Catalog=somevalue;Integrated Security=True;";
public Task JoinGroup()
{
return Groups.Add(Context.ConnectionId, "foo");
}
public DataTable GetDataTable(string strQuery)
{
SqlCommand objcmd;
SqlDataAdapter objda;
DataTable ds = new DataTable();
try
{
objconn = new SqlConnection(Connstr);
objconn.Open();
objcmd = new SqlCommand(strQuery, objconn);
objda = new SqlDataAdapter(objcmd);
objda.Fill(ds);
return ds;
}
catch (SqlException ex)
{
throw ex.InnerException;
}
finally
{
objconn.Close();
objcmd = null;
objda = null;
}
}
public override Task OnConnected()
{
int id = Convert.ToInt32(Context.QueryString["id"]);
string sql = string.Format("exec getfriend '" + id + "' ");
System.Data.DataTable dtgetfriend = GetDataTable(sql);
}}
Now when I am debugging I am not able to get my breakpoint hit on OnConnected. Why am I not able to start with this piece of code?
Also I have added this code in global.asax
public void Application_Start()
{
RouteTable.Routes.MapHubs();
}
You're not subscribed to the hub. Prior to start you need to declare at least one client side function and you need to reference your hub by the correct name. So if you modify your JS to be:
$(document).ready(function () {
var query = window.location.search;
var toRemove = '?id=';
var gorge = query.replace(toRemove, '');
// Proxy created on the fly
var hub = $.connection.chatHub2;
$.connection.hub.qs = "Id=" + gorge;
hub.client.foo = function() {};
// Start the connection
$.connection.hub.start(function () {
//chat.server.getAllOnlineStatus();
});
});
You'll be in good shape.

How to apply the backgroung colors in AutoCompleteExtender textbox values in asp.net?

i am binding two table values in AutoCompleteExtender but my requirement is differentiate the two tables apply the colors i.e table1 values apply red color and table2 values apply green color how to write the code pls give me any suggestion
my code is
[WebMethod]
public string[] GetCompletionList(string prefixText, int count)
{
if (count == 0)
{
count = 10;
}
DataTable dt = GetRecords(prefixText);
List<string> items = new List<string>(count);
for (int i = 0; i < dt.Rows.Count; i++)
{
string strName = dt.Rows[i][1].ToString() + ',' + dt.Rows[i][0].ToString();
items.Add(strName);
//items.Add(System.Drawing.Color.Red);
}
return items.ToArray();
}
Getrecords code is
public DataTable GetRecords(string strName)
{
SqlCommand cmd = new SqlCommand("Usp_Consultant1", LITRMSConnection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#consultantname", strName);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
LITRMSConnection.Open();
dAdapter.Fill(objDs);
LITRMSConnection.Close();
return objDs.Tables[0];
}
and stored procedure is
CREATE Procedure Usp_Consultant1
(#consultantname varchar(100))
As
Begin
select (cast(ConsultantID as varchar)+',Employee')as ConsultantID,(FirstName+LastName)as ConsultantName from Consultant where FirstName+LastName like +#consultantname+'%'
union all
select (cast(ConsID as varchar)+',NonEmployee')as ConsultantID,(Firstname+LastName)as consultantName from InDirectConsultant where FirstName+LastName like +#consultantname+'%'
ORDER BY 1;
End
pls give me any suggestion....
thank u
hemanth
answer is add the javascript function
function getCustomers_Populated(sender, e) {
var customers = sender.get_completionList().childNodes;
var searchText = sender.get_element().value;
for (var i = 0; i < customers.length; i++) {
var customer = customers[i];
var customerValueArray = (customer._value).split(",");
var customerId = customerValueArray[0];
var type = customerValueArray[2];
customers[i].innerHTML = customerId;
if (type == 'Employee') {
customers[i].style.backgroundColor = 'red';
}
else {
customers[i].style.backgroundColor = 'blue';
}
}
To selectively apply background colors to the autocompleteextender items you will probably have to use JavaScript.
Since all the items from one table contain the string ',Employee' and the items from the other contain ',NonEmployee' you can use that information for styling.
Set the properties:
OnClientShown="autoCompleteShow"
CompletionListItemCssClass="AutoCompleteExtender_CompletionListItem"
on the AutoCompleteExtender.
Inside autoCompleteShow we style the <li> items background color according to the table from which they came:
<script type="text/javascript">
function autoCompleteShow() {
var elements = document.getElementsByClassName('AutoCompleteExtender_CompletionListItem');
for (var i = 0; i < elements.length; i++)
if (elements[i].innerHTML.search(",Employee") != -1)
elements[i].style.setProperty("background-color", "#4CC417", "!important");
else
elements[i].style.setProperty("background-color", "Red", "!important");
}
</script>
Working demo code:
[WebForm1.aspx]
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="AutoCompleteExtenderContextualItemBgColor.WebForm1" %>
<%# Register TagPrefix="asp" Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.AutoCompleteExtender_CompletionListItem
{
color : White;
}
.AutoCompleteExtender_HighlightedItem
{
color : Black;
}
</style>
<script type="text/javascript">
function autoCompleteShow() {
var elements = document.getElementsByClassName('AutoCompleteExtender_CompletionListItem');
for (var i = 0; i < elements.length; i++)
if (elements[i].innerHTML.search(",Employee") != -1)
elements[i].style.setProperty("background-color", "#4CC417", "!important");
else
elements[i].style.setProperty("background-color", "Red", "!important");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="Server" />
<asp:TextBox runat="server" ID="myTextBox" Width="250" />
<asp:AutoCompleteExtender runat="server"
ID="myAutoCompleteExtender"
TargetControlID="myTextBox"
ServicePath="AutoComplete.asmx"
ServiceMethod="GetCompletionList"
CompletionListItemCssClass="AutoCompleteExtender_CompletionListItem"
CompletionListHighlightedItemCssClass="AutoCompleteExtender_HighlightedItem"
OnClientShown="autoCompleteShow">
</asp:AutoCompleteExtender>
</div>
</form>
</body>
</html>
[AutoComplete.asmx(markup)]
<%# WebService
Language="C#"
CodeBehind="~/App_Code/AutoComplete.cs"
Class="AutoComplete" %>
[~/App_Code/AutoComplete.cs]
using System;
using System.Collections.Generic;
using System.Web.Services;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class AutoComplete : WebService
{
public AutoComplete()
{
}
[WebMethod]
public string[] GetCompletionList(string prefixText, int count)
{
if (count == 0)
{
count = 10;
}
List<string> items =
new List<string>() { "test1 ,Employee Hgeurg Jfheuf",
"test2 ,NonEmployee Uheure Iueir",
"test3 ,Employee Jufhwiufhiwe Leroe",
"test5 ,Employee Cgrejg Jehure Byer",
"test7 ,NonEmployee Qewrerffx Yegr" };
return items.ToArray();
}
}

JQuery AutoComplete Source Issue C#

I am trying to get a simple example of how to us the AutoComplete JQuery plug-in work but running into some issue. The code is written in C# (2008) without using MVC.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css" type="text/css" media="all" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
//GetFormulary();
LoadAutoComplete();
});
function LoadAutoComplete() {
$("#quickSearchTextBox").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/WebSite1/Default.aspx/GetTest2",
data: "{}",
dataType: "json",
success: function(data) {
response($.map(data, function(item) {
return {
label: item.TestName,
value: item.TestName
}
}));
}
});
},
minLength: 2
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table id="quickSearchTable" border="0">
<tbody>
<tr>
<td>
<input style="width: 100%" id="quickSearchTextBox" title="Enter search words" maxlength="200" value="" />
</td>
</tr>
</tbody>
</table>
<div id="searchResults" style="display: none;">
</div>
</div>
</form>
</body>
</html>
Code Behind:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Web.Services;
using System.Web.UI;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string GetTest1()
{
return GetFTest2("art");
}
private static string GetFTest2(string searchPhrase)
{
var formularyTests = new List<FormularyTest>();
const string connectionString = "";
using (var sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
var sqlCommand = new SqlCommand("Search", sqlConnection) { CommandType = CommandType.StoredProcedure };
sqlCommand.Parameters.Add(new SqlParameter("#Phrase", searchPhrase));
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
while (sqlDataReader.Read())
{
formularyTests.Add(new FormularyTest { Name = sqlDataReader["LongName"].ToString() });
}
}
var jSearializer = new JavaScriptSerializer();
return jSearializer.Serialize(formularyTests);
}
[WebMethod]
public static List<FormularyTest> GetTest2()
{
return GetFTest1("arterial");
}
private static List<FormularyTest> GetFTest1(string searchPhrase)
{
var formularyTests = new List<FormularyTest>();
const string connectionString = "";
using (var sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
var sqlCommand = new SqlCommand("Search", sqlConnection) { CommandType = CommandType.StoredProcedure };
sqlCommand.Parameters.Add(new SqlParameter("#Phrase", searchPhrase));
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
while (sqlDataReader.Read())
{
formularyTests.Add(new FormularyTest { Name = sqlDataReader["LongName"].ToString() });
}
}
return formularyTests;
}
}
public class FormularyTest
{
public string Name { get; set; }
public string Url { get; set; }
}
For some reason I cannot get anything to show up in the textbox. A little help would be much appreciated.
The JavaScriptSerializer is returning a result in the format of:
{d:"[{\"Name\":\"Test 1\",\"Url\":\"url1\"},{\"Name\":\"Test 2\",\"Url\":\"url2\"}]"}
So, data.d would give you your serialized string [{"Name":"Test 1","Url":"url1"},{"Name":"Test 2","Url":"url2"}]. That woudl be closer to what you want, but you're really after a JSON array version of that string. If you use eval(data.d) instead of data in your success function, it will work. Admittedly, using eval is an imperfect solution, but it does allow your code to "work".
The following JavaScript has the change:
function LoadAutoComplete() {
$("#quickSearchTextBox").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Service.asmx/Test",
data: "{'searchTerm':'" + request.term + "'}",
dataType: "json",
async: true,
success: function (data) {
response($.map(eval(data.d), function (item) {
return {
label: item.Name,
value: item.Url
}
}));
},
error: function (result) {
alert("Error loading the data");
}
});
},
minLength: 2
});

problem getting dynamic xml

i have an ASP.net page that generates dynamic xml but the get statement of a jquery ajax request won't recognize the file. this solution worked with a php doc getting the dynamic xml. The asp.net page that generates xml works fine. The ajax request never succeeds. any ideas as to why much appreciated
<%# Page Language="C#" AutoEventWireup="true" Debug="true" ContentType="text/xml" %>
<%# Import Namespace="System.Xml" %>
<%# Import Namespace="System.Data.SqlClient" %>
<%# Import Namespace="System.Data" %>
<script runat="server">
protected void Page_Load(object source, EventArgs e)
{
XmlDocument doc = new XmlDocument();
// XML declaration
XmlNode declaration = doc.CreateNode(XmlNodeType.XmlDeclaration, null, null);
doc.AppendChild(declaration);
// Root element: article
XmlElement root = doc.CreateElement("statements");
doc.AppendChild(root);
string connStr = "";
string sqlStr = "SELECT [title], [statement] FROM [a table]";
using (SqlConnection connection = new SqlConnection(connStr))
{
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = sqlStr;
connection.Open();
using (SqlDataReader dataReader = command.ExecuteReader())
{
int indexOftitle = dataReader.GetOrdinal("title");
int indexOfstatement = dataReader.GetOrdinal("statement");
while (dataReader.Read())
{
string title = (string)dataReader.GetValue(indexOftitle);
string statement = (string)dataReader.GetValue(indexOfstatement);
XmlElement xstatement = doc.CreateElement("statement");
root.AppendChild(xstatement);
XmlAttribute xtitle = doc.CreateAttribute("title");
xtitle.Value = title;
xstatement.Attributes.Append(xtitle);
XmlAttribute xtext = doc.CreateAttribute("text");
xtext.Value = statement;
xstatement.Attributes.Append(xtext);
}
}
connection.Close();
}
}
doc.Save(Response.OutputStream);
}
</script>
<script type="text/javascript">
$.ajax({
type: "GET",
url: "../data/genxml_docstate.aspx",
dataType: "xml",
success: parseXml
});
});
function parseXml(xml) {
alert("ok");
var items = [];
var header = 'some initial html'
$(xml).find("statement").each(function () {
var title = $(this).attr("title");
var titleid = (title.substr(0, 8)).replace(" ", "_");
items.push('<li id="' + titleid + '">' + title + '</li>');
});
$('#doclist').append(items.join(''));
$("#doc_box_right").html(header);
$(xml).find("statement").each(function () {
var title = $(this).attr("title");
var titleid = (title.substr(0, 8)).replace(" ", "_");
var id = '#' + titleid;
var statement = $(this).attr("text");
$(id).css("cursor", "pointer");
$(id).mouseover(function () {
$(id).css("background-color", "gray");
$("#doc_box_right").html('<h2>' + title + '</h2><p>' + statement + '</p>');
});
$(id).mouseleave(function () {
$(id).css("background-color", "transparent");
$("#doc_box_right").html(header);
});
});
}
</script>
#Chris , can you try firebug .net panel and see if you are getting results for the ajax...so that we can eliminate the issue.It shows the errors also if there are any.
You are not setting the mime type of the response to text/xml, so the browser will not recognize it as XML.
Make sure you add a:
Response.ContentType("text/xml");
before you save to the output stream.

Resources