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
});
Related
finally I know how to call the method in the server and the client will refresh the chart. if you update data on table, the chart will adjust automatically. the code as below:
this is my html code:
<div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="Scripts/jquery.signalR-2.2.1.min.js"></script>
<script src="../signalR/hubs"></script>
<script type="text/javascript">
$(function () {
//proxy created on the fly
var job = $.connection.statisticsHub;
//declare a function on the job hub so the server can invoke it
job.client.displayStatus = function () {
getData();
};
//start the connection
$.connection.hub.start()
.done(function () {
console.log('now connected');
//execute function in client from server
job.server.show();
})
.fail(function (error) {
console.log('error nih: ' + error);
});
});
function getData() {
//alert("from getData");
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var options = {
title: 'USA City Distribution'
};
$.ajax({
type: "POST",
url: "Default.aspx/GetChartData",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var data = google.visualization.arrayToDataTable(r.d);
var chart = new google.visualization.PieChart($("#chart")[0]);
chart.draw(data, options);
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
}
</script>
<div id="chart" style="width: 900px; height: 500px;">
</div>
this is Hub:
using Microsoft.AspNet.SignalR;
namespace TutorialGooglePieChart
{
public class StatisticsHub : Hub
{
public void Show()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<StatisticsHub>();
context.Clients.All.displayStatus();
}
}
}
this is my cs file:
using System;
using System.Collections.Generic;
using System.Data;
using System.Web.Services;
using System.Configuration;
using System.Data.SqlClient;
namespace TutorialGooglePieChart
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static List<object> GetChartData()
{
string query = "SELECT Name, Quantity FROM [dbo].[Products]";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
List<object> chartData = new List<object>();
chartData.Add(new object[]
{
"Name", "Quantity"
});
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.Notification = null;
SqlDependency.Start(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
SqlDependency dependency = new SqlDependency(cmd);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
chartData.Add(new object[]
{
sdr["Name"], sdr["Quantity"]
});
}
}
con.Close();
return chartData;
}
}
}
private static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
StatisticsHub myHub = new StatisticsHub();
myHub.Show();
}
}
}
}
thank you for your help
Without testing it, the java script looks okay.
Your method needs to be updated, remove static from your method, not positive but I think that is where your main problem is. Comment out the IHubContext as I don't believe it is needed since you are within the hub. I think that is for calling methods (in your hub) from other classes.
Also, changing Clients.All to Clients.Caller. It would not make sense to update everyone's chart when anyone connects. Rather only the calling client.
Try changing to this:
using Microsoft.AspNet.SignalR;
namespace TutorialGooglePieChart
{
public class StatisticsHub : Hub
{
public void Show()
{
//IHubContext context = GlobalHost.ConnectionManager.GetHubContext<StatisticsHub>();
//context.Clients.All.displayStatus();
context.Clients.Caller.displayStatus();
}
}
}
<%# 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.
I click my edit button,it enters button click function in javascript.When ajax() is executed the control goes to page load of WebForm rather than directly calling update() of webform which I'm mentioning as [ url: "WebForm1.aspx/update",] in ajax().Why not my update function is invoked ??
I'm having master page for my webform and the button is an asp:control
This is my javascript
$(document).ready(function () {
$("input[id*='edit']").click(function () {
var userdata = {};
userdata["Name"]="Saran";
var DTO = { 'userdata' : userdata};
$.ajax({
type: "POST",
contenttype: "application/json; charset=utf-8",
url: "WebForm1.aspx/update",
data: JSON.stringify(DTO),
datatype: "json",
success: function (result) {
//do something
alert("SUCCESS = " + result);
console.log(result);
},
error: function (xmlhttprequest, textstatus, errorthrown) {
alert(" conection to the server failed ");
console.log("error: " + errorthrown);
}
});//end of $.ajax()
return false;
});//eof button click
});
and my webform looks like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using Payoda.Assignments.BusinessLayer;
namespace Payoda.Assignments.LoginApplication
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string update(string userdata)
{
return "success";
}
}
}
my aspx page looks like this
<%# Page Title="" Language="C#" MasterPageFile="~/MyMasterPage.Master" AutoEventWireup="true" CodeBehind="TrialPage.aspx.cs" Inherits="Application.TrialPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script src="Scripts/jquery-1.10.2.js"></script>
<script src="Scripts/TrialScript.js"></script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="Contents" runat="server">
<asp:Button ID="editLink" runat="server" Text="MY BUTTON" />
</asp:Content>
I found the mistake...
one of the $.ajax parameters which is contentType is written wrongly as contenttype whereas the correct format is "contentType"...
You should use a regular html input instead of asp:button
I don't know where the problem is, my code looks fine and I tried hard, but getting error all the time.
Here is my code:
Markup:
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#Button1").click(function(){
var Name=document.getElementById('Text1').value
var Class=document.getElementById('Text2').value
var Data=JSON.stringify({Name:Name,Class:Class});
alert(Data);
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Default.aspx/InsertData',
data:Data,
async: false,
success: function (response) {
$('#Text1').val('');
$('#Text2').val('');
},
error: function () {
alert("Error")
}
});
});
});
</script>
ASP.NET AJAX Page Method in code-behind:
[WebMethod]
public string InsertData(string Name, string Class)
{
SqlCommand cmd = new SqlCommand("Insert into employee(EmployeeName,Class) values(#EmpName,#Classs)",con);
cmd.Parameters.AddWithValue("#EmpName", Name);
cmd.Parameters.AddWithValue("#Classs",Class);
cmd.ExecuteNonQuery();
con.Close();
return "True";
}
Try this:
Method must be static if it is in aspx page code behind
[WebMethod]
public static string InsertData(string Name, string Class)
{
SqlCommand cmd = new SqlCommand("Insert into employee(EmployeeName,Class) values(#EmpName,#Classs)",con);
cmd.Parameters.AddWithValue("#EmpName", Name);
cmd.Parameters.AddWithValue("#Classs",Class);
cmd.ExecuteNonQuery();
con.Close();
return "True";
}
You don't need to stringify it.
Without stringifying just pass
"{'Name':'"+Name+"','Class':'"+Class+"'}"
If you want to pass the stringified object it must be as shown below
JSON.stringify({'Name':Name,'Class':Class});
See the Quotes added.
var Data=JSON.stringify({'Name':Name,'Class':Class});
alert(Data);
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Default.aspx/InsertData',
data:Data,
async: false,
success: function (response) {
$('#Text1').val('');
$('#Text2').val('');
},
error: function ()
{ alert("Error") }
});
And in the page back code
[WebMethod]
public string InsertData(myobj getdat)
{
SqlCommand cmd = new SqlCommand("Insert into employee(EmployeeName,Class) values(#EmpName,#Classs)",con);
cmd.Parameters.AddWithValue("#EmpName", getdat.Name);
cmd.Parameters.AddWithValue("#Classs",getdat.Class);
cmd.ExecuteNonQuery();
con.Close();
return "True";
}
public class myobj
{
public string Name {get;set;}
public string Class{get;set;}
}
ASP.NET AJAX Page Methods must be static, change your code to this:
[WebMethod]
public static string InsertData(string Name, string Class)
{
SqlCommand cmd = new SqlCommand("Insert into employee(EmployeeName,Class) values(#EmpName,#Classs)",con);
cmd.Parameters.AddWithValue("#EmpName", Name);
cmd.Parameters.AddWithValue("#Classs",Class);
cmd.ExecuteNonQuery();
con.Close();
return "True";
}
Read Why do ASP.NET AJAX page methods have to be static? for an explanation as to why.
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.