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();
}
}
}
Related
I can not do how to implement google recaptcha v3 in Contact us webform in ASP .NET(not in MVC).
please help me to short out this problem.
In the ASPX page put the following code at the top after the <asp:Content ID="Content2" ContentPlaceholderID="maincontent" runat="server">
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script>
function popup() {
swal({
title: "Successful!",
text: "Your enquiry is submitted. Thank you for contacting us.",
icon: "success",
button: "Ok",
});
}
function popupservererror() {
swal({
title: "Server Error!",
text: "Server error ! Try again later.",
icon: "error",
button: "Ok",
});
}
function errorcaptcha() {
swal({
title: "Catcha Error!",
text: "Captch error ! Try again later.",
icon: "error",
button: "Ok",
});
}
</script>
<script src="https://www.google.com/recaptcha/api.js?render=6LfYRxseAAAAAMwj0viw_tsfmSlEyQkYxodlzaRT"></script> /*Site Key*/ /*6LerAgceAAAAAFoTUoO95pkxDqaoM8kgZVz9NdK_*/
<script>
grecaptcha.ready(function () {
grecaptcha.execute('6LfYRxseAAAAAMwj0viw_tsfmSlEyQkYxodlzaRT', { action: 'contact_us' }).then(function (token) {
document.getElementById("<%=hf_token.ClientID%>").value = token;
});
});
</script>
<script src="http://www.google.com/recaptcha/api.js?render=6LfYRxseAAAAAMwj0viw_tsfmSlEyQkYxodlzaRT"></script>
<script>
grecaptcha.ready(function () {
grecaptcha.execute('6LfYRxseAAAAAMwj0viw_tsfmSlEyQkYxodlzaRT', { action: 'contact_us' }).then(function (token) { //6LerAgceAAAAAFoTUoO95pkxDqaoM8kgZVz9NdK_//
$.ajax({
type: "POST",
url: "Default.aspx/SetToken",
data: JSON.stringify({ _token: token }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log('Passed the token successfully');
},
failure: function (response) {
alert(response.d);
}
});
});
});
</script>
<script src="js/main.js"></script>
And now see the below code for ASPX.CS page for the actions.
using App.BAL.Master;
using App.BAL.Utility;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI;
namespace Supplychain_cms.contact
{
public partial class index : System.Web.UI.Page
{
private string recaptchaSecret = "6LfYRxseAAAAAKu__YvhSPEQVJBVunOeeutWN8ro"; /*Secret Key --- 6LerAgceAAAAAM7gGAKouqHnz7w9KwrI25OnIjyw*/
private string Token = string.Empty;
private ResponseToken response = new ResponseToken();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_Submit_click(object sender, EventArgs e)
{
try
{
if (CaptchaVerify().Success)
{
string to_username = ConfigurationManager.AppSettings["to_username"].ToString();
string form_username = ConfigurationManager.AppSettings["form_username"].ToString();
string form_password = ConfigurationManager.AppSettings["form_password"].ToString();
string smtpAddress = "smtppro.zoho.in";
int portNumber = 587;
bool enableSSL = true;
using (MailMessage mail = new MailMessage())
{
string template = File.ReadAllText(Server.MapPath("~/main-assets/components/contactmail.html"));
template = template.Replace("FULLNAME", txt_Name.Value);
template = template.Replace("EMAILID", txt_Email.Value);
template = template.Replace("MESSAGE", txt_Message.Value);
mail.From = new MailAddress(form_username, "Supply Chain");
mail.To.Add(to_username);
mail.Subject = "New appointment query from " + txt_Name.Value + " for SuplyChain";
mail.Body = template.ToString();
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(form_username, Encrypt.Decryptdata(form_password));
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
}
using (MailMessage mail = new MailMessage())
{
string template = File.ReadAllText(Server.MapPath("~/main-assets/components/contactreply.html"));
template = template.Replace("FULLNAME", txt_Name.Value);
mail.From = new MailAddress(form_username, "Supply Chain");
mail.To.Add(txt_Email.Value);
mail.Subject = "Thank you for contacting on Supply Chain";
mail.Body = template.ToString();
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(form_username, Encrypt.Decryptdata(form_password));
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
}
Page.ClientScript.RegisterStartupScript(GetType(), "popup", "popup();", true);
txt_Name.Value = "";
txt_Email.Value = "";
txt_Message.Value = "";
}
else
{
Page.ClientScript.RegisterStartupScript(GetType(), "popup", "errorcaptcha();", true);
txt_Name.Value = "";
txt_Email.Value = "";
txt_Message.Value = "";
}
}
catch (Exception ex)
{
Page.ClientScript.RegisterStartupScript(GetType(), "popupservererror", "popupservererror(); console.log('" + ex.Message + "');", true);
}
}
public ResponseToken CaptchaVerify()
{
//It should only call once
if (response.score == 0)
{
Token = hf_token.Value;
var responseString = RecaptchaVerify(Token);
response = JsonConvert.DeserializeObject<ResponseToken>(responseString.Result);
}
return response;
}
private string apiAddress = "https://www.google.com/recaptcha/api/siteverify";
private async Task<string> RecaptchaVerify(string recaptchaToken)
{
string url = $"{apiAddress}?secret={recaptchaSecret}&response={recaptchaToken}";
using (HttpClient httpClient = new HttpClient())
{
try
{
string responseString = httpClient.GetStringAsync(url).Result;
return responseString;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
public class ResponseToken
{
public DateTime challenge_ts { get; set; }
public float score { get; set; }
public List<string> ErrorCodes { get; set; }
public bool Success { get; set; }
public string hostname { get; set; }
}
}
}
Now go the Web.config file for Database connection.
<connectionStrings>
<add name="CON_NAME" connectionString="Data Source=localhost;
Initial Catalog=db_SUPPLY_CHAIN; User ID=sa;
Password=jagannath29" providerName="System.Data.SqlClient" />
</connectionStrings>
I have the following code which displays live data using SignalR. The table gets updated instantly using SignalR once a row is inserted, updated, or deleted. However, I would like to know in particular the type of change that happened to the database (whether it's an update, delete, or insert). I understand that the onchange() method detects changes on the database, but how can I determine what type of change it is?
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionCustomer"].ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(#"SELECT [Id],[CustomerName] FROM [CustomerInfoes] ", connection))
{
// Make sure the command object does not already have
// a notification object associated with it.
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
SqlDataReader reader = command.ExecuteReader();
var listCus = reader.Cast<IDataRecord>()
.Select(x => new
{
Id = (int)x["Id"],
CustomerName = (string)x["CustomerName"],
}).ToList();
return Json(new { listCus = listCus }, JsonRequestBehavior.AllowGet);
}
}
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
CustomerHub.Show();
}
Hub:
public static void Show()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<CustomerHub>();
context.Clients.All.displayCustomer();
}
View
<script src="~/signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var cus = $.connection.customerHub;
// Declare a function on the job hub so the server can invoke it
cus.client.displayCustomer = function () {
getData();
};
// Start the connection
$.connection.hub.start();
getData();
});
function getData() {
var $tbl = $('#tblInfo');
$.ajax({
url: $("#Get").val(),
type: 'GET',
datatype: 'json',
success: function (data) {
$tbl.empty();
$.each(data.listCus, function (i, model) {
$tbl.append
(
'<tr>' +
'<td>' + model.Id + '</td>' +
'<td>' + model.CustomerName + '</td>' +
'<tr>'
);
});
}
});
}</script>
You can easily find out the change type by looking at eventArgs.Info property.
I am trying to visualize data using google charts.But the chart is not displaying.I want to display data which is retrieved from sqlserver database
here is my code.
<div id="chart_div" style="width:500px;height:400px">
<%-- Here Chart Will Load --%>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
var jdata = $.ajax({
url: "GetData.aspx",
dataType: "json",
async: false
}).responseText;
var data = new google.visualization.DataTable(jData);
var options = {
title: 'Chess opening moves',
width: 900,
legend: { position: 'none' },
chart: {
title: 'Chess opening moves',
subtitle: 'popularity by percentage'
},
bars: 'horizontal', // Required for Material Bar Charts.
axes: {
x: {
0: { side: 'top', label: 'amount' } // Top x-axis.
}
},
bar: { groupWidth: "90%" }
};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, options);
};
</script>
</div>
GetData.aspx
public partial class GetData : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
JavaScriptSerializer js = new JavaScriptSerializer();
string arr = JsonConvert.SerializeObject(get(), Formatting.None,
new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
Response.Write(arr);
}
private object get()
{
List<object> ls = new List<object>();
SqlConnection con = new SqlConnection("Data Source=dell-pc;Initial Catalog=hospital;Integrated Security=True");
SqlCommand cmd = new SqlCommand("select top(5) p_id, amount from payments", con);
con.Open();
DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
ls.Add(dr);
}
return ls;
}
}
The JsonArray loads as follows.
[{"RowError":"","RowState":2,"Table":[{"p_id":"PT1","amount":7000.0000},{"p_id":"PT2","amount":35000.0000},{"p_id":"PT8","amount":95000.0000},{"p_id":"PT10","amount":51000.0000},{"p_id":"PT3","amount":1200.0000}],"ItemArray":["PT1",7000.0000],"HasErrors":false},{"RowError":"","RowState":2,"Table":[{"p_id":"PT1","amount":7000.0000},{"p_id":"PT2","amount":35000.0000},{"p_id":"PT8","amount":95000.0000},{"p_id":"PT10","amount":51000.0000},{"p_id":"PT3","amount":1200.0000}],"ItemArray":["PT2",35000.0000],"HasErrors":false},{"RowError":"","RowState":2,"Table":[{"p_id":"PT1","amount":7000.0000},{"p_id":"PT2","amount":35000.0000},{"p_id":"PT8","amount":95000.0000},{"p_id":"PT10","amount":51000.0000},{"p_id":"PT3","amount":1200.0000}],"ItemArray":["PT8",95000.0000],"HasErrors":false},{"RowError":"","RowState":2,"Table":[{"p_id":"PT1","amount":7000.0000},{"p_id":"PT2","amount":35000.0000},{"p_id":"PT8","amount":95000.0000},{"p_id":"PT10","amount":51000.0000},{"p_id":"PT3","amount":1200.0000}],"ItemArray":["PT10",51000.0000],"HasErrors":false},{"RowError":"","RowState":2,"Table":[{"p_id":"PT1","amount":7000.0000},{"p_id":"PT2","amount":35000.0000},{"p_id":"PT8","amount":95000.0000},{"p_id":"PT10","amount":51000.0000},{"p_id":"PT3","amount":1200.0000}],"ItemArray":["PT3",1200.0000],"HasErrors":false}]
I think there is something wrong when json is loading. please help
The main reason here that you fail to load json data is probably because you use a full aspx page GetData.aspx (and there you send wrong header, content type)
Change that to a handler, make a new handler not just rename the page, something like getdata.ashx and place there your code.
Be sure to send the correct content type context.Response.ContentType, and check that you send only the correct json data
the answers here can help : ASP.NET Returning JSON with ASHX
I want to create a grid and automatic update it, when data changes in the database. It works with a simple table control.
public partial class index : System.Web.UI.Page
{
static string connectionString = #"Data Source=*******;initial catalog=Test;persist security info=True; Integrated Security=SSPI;";
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static IEnumerable<Person> GetData()
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(#"SELECT [Id],[Name] FROM [dbo].[Persons]", connection))
{
command.Notification = null;
SqlDependency.Start(connectionString);
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(Dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
using (var reader = command.ExecuteReader())
return reader.Cast<IDataRecord>()
.Select(x => new Person(x.GetInt32(0), x.GetString(1))).ToList();
}
}
}
private static void Dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
MyHub.Show();
}
public void FillGrid()
{
List<Person> persons = new List<Person>();
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(#"SELECT [Id],[Name] FROM [dbo].[Persons]", connection))
{
if (connection.State == ConnectionState.Closed)
connection.Open();
using (SqlDataReader rdr = command.ExecuteReader())
{
while (rdr.Read())
{
var id = rdr.GetInt32(0);
var name = rdr.GetString(1);
persons.Add(new Person(id, name));
}
}
}
}
grid.DataSource = persons;
grid.DataBind();
}
}
public class MyHub : Hub
{
public static void Show()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
context.Clients.All.displayStatus();
}
}
And the apsx Page :
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.6.4.min.js"></script>
<script src="Scripts/jquery.signalR-2.2.2.min.js"></script>
<script src="signalr/hubs"></script>
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var job = $.connection.myHub;
// Declare a function on the job hub so the server can invoke it
job.client.displayStatus = function () {
getData();
};
// Start the connection
$.connection.hub.start();
getData();
});
function getData()
{
var $tbl = $('#tbl');
$.ajax({
url: '/index.aspx/GetData',
contentType: 'application/json;charset=utf-8',
datatype: 'json',
type: 'POST',
success: function (data) {
if (data.d.length > 0) {
var newdata = data.d;
$tbl.empty();
$tbl.append(' <tr><th>ID</th><th>Name</th></tr>');
var rows = [];
for (var i = 0; i < newdata.length; i++) {
rows.push(' <tr><td>' + newdata[i].Id + '</td><td>' + newdata[i].Name + '</td><td></tr>');
}
$tbl.append(rows.join(''));
}
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table id="tbl"></table>
<dx:ASPxGridView ID="grid" runat="server"></dx:ASPxGridView>
</div>
</form>
</body>
</html>
However I want to use a Devepress Aspxgridview. The Devexpress Site states they don't support SignalR. However since the Javascript function is triggered when data changes in the database, is it possible somehow to force the client to get the data from the server? Force a postback and/or call the FillGrid method? ( To create the grid from js is not possible since the AspxgridView Control is much more complicated).
SOURCE: https://www.youtube.com/watch?v=30m-7wpmbrc
Although SignalR is not supported out of the box, it should be possible to manually notify the server side about the update using the existing API. You can send a callback to the server using the ASPxClientGridView.PerformCallback method, and handle the server side ASPxGridView.CustomCallback event to reload data from the SQL server.
I have written the fallowing ashx code. for autocomplete textbox.
i want to transfer the values ContactId, ContactName from ashx to code behind in aspx file.
how can i do that
code for ashx file
<%# WebHandler Language="C#" Class="Search_CS" %>
using System;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
public class Search_CS : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string prefixText = context.Request.QueryString["q"];
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["constr"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select ContactId, ContactName from Customers where " +
"ContactName like #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
cmd.Connection = conn;
StringBuilder sb = new StringBuilder();
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
sb.Append(sdr["ContactName"])
.Append(Environment.NewLine);
}
}
conn.Close();
context.Response.Write(sb.ToString());
}
}
}
public bool IsReusable {
get {
return false;
}
}
}
code for aspx file
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="css/jquery.autocomplete.css" rel="stylesheet" type="text/css" />
<script src="scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="scripts/jquery.autocomplete.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#<%=txtSearch.ClientID%>").autocomplete('Search_CS.ashx');
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>
try this
in aspx page
<div>
<script type="text/javascript">
function get_look_suggs(key, cont) {
var script_name = 'Search_CS.ashx';
var params = { 'q': $("#<%=txtSearch.ClientID%>").val() }
$.get(script_name, params,
function (obj) {
// obj is just array of strings
var res = [];
for (var i = 0; i < obj.length; i++) {
res.push({ id: i, value: obj[i].Name });
}
// will build suggestions list
cont(res);
},
'json');
}
$(document).ready(function () {
$("#<%=txtSearch.ClientID%>").autocomplete({ ajax_get: get_look_suggs });
});
</script>
<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
</div>
in handler
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Data.SqlClient;
using System;
using System.Data;
public class Search_CS : IHttpHandler
{
private readonly JavaScriptSerializer js = new JavaScriptSerializer();
public class names
{
public names(string p)
{
// TODO: Complete member initialization
this.Name = p;
}
public string Name { get; set; }
}
// Handle request based on method
public bool IsReusable { get { return false; } }
public void ProcessRequest(HttpContext context)
{
string prefixText = context.Request.QueryString["q"];
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["constr"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select ContactId, ContactName from Customers where " +
"ContactName like #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
cmd.Connection = conn;
conn.Open();
List<names> lstnew = new List<names>();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
lstnew.Add(new names(sdr["ContactName"].ToString()));
}
}
conn.Close();
string jsonObj = js.Serialize(lstnew);
context.Response.AddHeader("Content-Disposition", "inline; filename=\"files.json\"");
context.Response.Write(jsonObj);
context.Response.ContentType = "application/json";
}
}
}
}