Asp.Net Ajax Select Sql Query - asp.net

Hello everyone I want to do ajax select query with parameters. I get select query but I want to do if writen on textbox doesnt have, get message "dont have this query".
Ajax Code..
<script type="text/javascript">
$(document).ready(function () {
$("#ekle").click(function () {
$('#ajaxloading').show();
$("#data").html("");
$.ajax({
type: "POST",
url: "Default.aspx/ekle",
data: "{'id':'" + txtemail.value + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$('#ajaxloading').hide();
$("#data").html(msg.d);
},
error: function () {
if (txtemail.value == "") {
alert('Boş alan bırakmayın..');
$('#ajaxloading').hide();
}
else {
alert('Talep esnasında sorun oluştu. Yeniden deneyin');
$('#ajaxloading').hide();
}
}
});
});
});
</script>
Web Method Code
Web Method Kodlarım
[System.Web.Services.WebMethod]
public static string ekle(int id)
{
System.Threading.Thread.Sleep(1000);
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("GonderiNo");
dt.Columns.Add("Tarih");
dt.Columns.Add("GonderenAdSoyad");
dt.Columns.Add("AliciAdSoyad");
dt.Columns.Add("Adres");
dt.Columns.Add("Durum");
using (KargoTakipEntities kargo = new KargoTakipEntities())
{
var kargotakip = from v in kargo.KargoTakipSorgu where v.GonderiNo== id select v;
int i = 0;
foreach (var k in kargotakip)
{
dt.Rows.Add();
dt.Rows[i]["ID"] = k.ID;
dt.Rows[i]["GonderiNo"] = k.GonderiNo;
dt.Rows[i]["Tarih"] = k.Tarih;
dt.Rows[i]["GonderenAdSoyad"] = k.GonderenAdSoyad;
dt.Rows[i]["AliciAdSoyad"] = k.AliciAdSoyad;
dt.Rows[i]["Adres"] = k.Adres;
dt.Rows[i]["Durum"] = k.Durum;
i++;
}
GridView g = new GridView();
g.ShowHeader = false;
g.BorderWidth = 2;
g.CellPadding = 15;
g.CellSpacing = 15;
g.GridLines = GridLines.Both;
g.DataSource = dt;
g.DataBind();
StringWriter sw = new StringWriter();
HtmlTextWriter ht = new HtmlTextWriter(sw);
g.RenderControl(ht);
return sw.ToString();
}
}

Related

How can I know the type of change happened to the database using SQL Dependency

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.

How to send data using Json and get in asp.net services

I am php developer and recently switched to asp, I want to send data to web services and get there but I am unable to come up with a solution.
In php if you want to access data for back-end process purpose we simply use
.Serialize(); method,
for example:
<form id="loginForm">
<input class="form-control" name="UserEmail" placeholder="Email" type="email" required=""/>
</form>
and in Jscript function we will serialize the form, e.g:
var data = $("#loginForm").serialize();
and in process side I can call it by inputs name, But in asp.net I am unable to do the same, I might be missing something or does asp.net do not support such approach at all? I do not know please programmers help me out.
You should use Id property and use stingify() method instead of serialization.
HTML
<input class="form-control" Id="UserEmail" placeholder="Email" type="email" required=""/>
JS
function YesFunction() {
var email= $("#UserEmail").val();
var d= [];
d.push(email);
var jsndta = JSON.stringify({ d: d});
$.ajax({
type: "POST",
url: "wbservices/SearchSchoolInfoAndInventory.asmx/Searchschoolbesicinfo",
data: jsnDta,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var rtnData = r.d; //all returned data...
var respDta = [];
$.map(rtnData, function (item, index) {
var j = [
item.status,
item.msg,
];
respDta.push(j);
});
$.each(respDta, function (key, value) {
var status = value[0];
var msg = value[1];
if (status == true) {
table.html(msg);
} else {
}
}); //1st out loop ends here...
},
error: function (jqXHR, textStatus, errorThrown) {
// $("#responseMovDetails").html(jqXHR + textStatus + errorThrown);
alert("error while loading Purchases Head" + jqXHR + textStatus + errorThrown);
}
});
}
Now create a class and create two public variables and call both variables by creating class object in web service class.
public class RequestResponse
{
public bool status { get; set; }
public string msg { get; set; }
}
[WebMethod]
public List<RequestResponse>ActivatePBudget(List<string> d)
{
RequestResponse r = new RequestResponse();
List<RequestResponse> list = new List<RequestResponse>();
string Email= d[0].ToString();
//establish connection. I have established connection in separate class.
DbCon dbcon = new DbCon();
string constr = dbcon.dbconnection();
SqlConnection con = new SqlConnection(constr);
try
{
con.Open();
string CheckEmail = "select * from Table_Name where Email= #m";
SqlCommand getcmd= new SqlCommand(CheckEmail,con);
getcmd.Parameters.AddWithValue("#m", Email);
SqlDataReader reader=getbhidcmd.ExecuteReader();
if(reader.Read())
{
r.status = true;
r.msg = "Valid User Or Redirect user to another page";
list.Add(r);
reader.Close();
}
else
{
reader.Close();
r.status = false;
r.msg = "Invalid Email";
list.Add(r);
}
}
catch (Exception ex)
{
r.status = false;
r.msg = "Invalid Email" + ex.ToString();
list.Add(r);
}
finally
{
con.Close();
}
return list;
}
HTML+JS+ WEB-SERVICE
JS:
<script type="text/javascript">
function getProject() {
var data = "";
var strUser = "<%=nowUser%>";
$.ajax({
type: 'post',
url: '<%=AppRoot%>main/BackWebservice.asmx/LoadProjects',
async: true,
dataType: 'json',
data: { strAdmin: strUser },
success: function (result) {
var json = eval(result); //数组
var optionstring = "";
$.each(json, function (index, item) {
//循环获取数据
var name = json[index].Name;
var idnumber = json[index].ID;
optionstring += "<option value=\"" + idnumber + "\" >" + name + "</option>";
});
$("#userProject").html("<option value=\"" + 0 + "\"'>所有项目</option> " + optionstring);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.readyState);
alert(textStatus);
}
});
}
</script>
WEB-SERVICE
[WebMethod]
public void LoadProjects(string strAdmin)
{
List<Project> mProjects = new List<Project>();
string stuJsonString = "";
bool bManager = false;
using (SqlConnection connection1 = new SqlConnection(Cfg.SqlServer))
{
connection1.Open();
string mstrsql1 = "SELECT * FROM ShuiUser where 账号='" + strAdmin + "'";
using (SqlCommand CMD1 = new SqlCommand(mstrsql1, connection1))
{
SqlDataReader DR1 = CMD1.ExecuteReader();
while (DR1.Read())
{
if (DR1["管理"].ToString() == "1")
{
bManager = true;
}
}
DR1.Close();
}
connection1.Close();
}
using (SqlConnection connection2 = new SqlConnection(Cfg.SqlServer))
{
connection2.Open();
string mstrsql2 = "";
if (bManager)
{
mstrsql2 = "select * from ShuiProject";
}
else
{
mstrsql2 = "select a.* from ShuiProject a,ShuiUser b where a.[编号]=b.[项目] AND b.[账号]='" + strAdmin + "' ";
}
using (SqlCommand CMD2 = new SqlCommand(mstrsql2, connection2))
{
SqlDataReader DR2 = CMD2.ExecuteReader();
while (DR2.Read())
{
Project mProject = new Project();
mProject.ID = Convert.ToInt16(DR2["编号"]);
mProject.Name = DR2["名称"].ToString();
mProjects.Add(mProject);
}
DR2.Close();
}
connection2.Close();
}
stuJsonString = JsonConvert.SerializeObject(mProjects);
//主要是下面的两句 The most important two sentences
Context.Response.Write(stuJsonString);
Context.Response.End();
}
ASPX:
<form runat=”server” id="loginForm">
<asp:Textbox runat=”server” cssClass="form-control" id="UserEmail" placeholder="Email" TextMode=”email” required=""/>
</form>
On Codebehind(.cs):
using Newtonsoft.Json;
var obj=new {
Email= UserEmail.Text.Trim()
};
var j=JsonConvert.SerializeObject(obj);
I have assumed that you are working on webforms.
you must used jsonp in asp
$.ajax({
url: 'you path',
datatype: 'jsonp',
data: {....}
});

ASP.NET: Relative Path with Root Operator('~') in Client side

I have implemented a web page with asp.net.
It has some ajax function.
in ajax function, Get a image path from server side webMethod.
The image path consist of root operator, for example "~/Images/Icons/SendEmail.png".
In Client side, I want to set image path to img element.
How can I set the image from this relative path?
Here is my code snippet.
Please refer this and give me some advices. Thank you in advance.
Clien side
function DrawImage() {
$.ajax({
type: 'POST',
url: '../Management/GetImage',
data: '{Index: "' + Index + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (resp) {
if (resp.d == null) {
return;
}
var ImagePath = resp.d;
var image = document.createElement('img');
image.src = ImagePath; // e.g. "~/Images/Image.png"
$(imageDiv).append(image);
},
error: function (msg) {
alert("Failed to Image: " + msg.statustext);
}
});
}
Server Side WebMethod
[WebMethod]
public static string GetImage(string Index)
{
string conStr = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(conStr);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "Select_ImagePath";
command.Parameters.AddWithValue("#Index", Index);
string imgPath = "";
try
{
conn.Open();
SqlDataReader dataReader = command.ExecuteReader();
if (dataReader.Read())
{
imgPath = (string)dataReader["Image_Path"]; // e.g. "~/Images/Image.png"
}
}
catch (Exception err)
{
}
finally
{
conn.Close();
}
return imgPath;
}
I solved this problem by just implementing some function in javascript like below.
function ConvertRelPathToAbsPath(path)
{
var absPath ="";
if (path.length > 0)
absPath = window.location.protocol + '//' + location.host + path.substr(1);
return absPath;
}

Binding Lable from webmethod using ajax

Hi guyes i am trying to read data from webmethod and pass the value to my lable in aspx page. for this i take a use of Ajax and webmethod. my problem is when i am not able to bind data on success to my lable controle.
my .asmx page.
public static string str;
[WebMethod]
public string GetEmployeeDetail(string name)
{
str = name;
Get(str);
string daresult;
daresult = Get(str);
return daresult;
}
[WebMethod]
public string Get(string str)
{
List<string> rst = new List<string>();
using (SqlConnection con = new SqlConnection("..."))
{
using (SqlCommand cmd = new SqlCommand("select practice_short_name from PRACTICE_DETAIL where Practice_Name = '" + str + "'",con))
{
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
rst.Add(string.Format("{0}", dr["practice_short_name"]));
}
System.Web.Script.Serialization.JavaScriptSerializer jSearializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return jSearializer.Serialize(rst);
}
}
}
and here is my ajax call function in aspx page.
function fun() {
var ddlpsn = document.getElementById("<%=ddlPSN.ClientID%>");
$(ddlpsn).change(function () {
var s = $(this).val();
$.ajax({
type: 'POST',
url: 'AutoCompleteService.asmx/GetEmployeeDetail',
data: '{name: "' + s + '" }',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
//i think i need to do some changes in here but not getting what to do.
$('#lblpriority').text(data.val);
},
error: function (error) {
console.log(error);
}
});
});
};
You need to change data.val to data.d. Data returned from WebMethod is contained in d property if you have not explicitly defined your own property for returned data.
$('#lblpriority').text(data.d);
You need to make your WebMethod static in order to called by ajax.

How can i see datatable which is the return from a webservice method

I am trying use a datatable from a web service method. I can see return value when it's a string data.
This my code and it returns an alert hatada : null
$.ajax(
{
type: 'POST',
url: 'http://localhost:40764/HastaTahlilUyariServisi.asmx/Hello',
data: "{_sTcKimlikNo: '111111111111', _iKlinikKodu:121212, _bAy:12, _iYil:2009}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(ajaxCevap) {
alert('basarili: ' + ajaxCevap); //$('#dv').html(ajaxCevap.d);
},
error: function(xhr, status) {
alert("hatada:" + xhr.responseXML);
},
beforeSend: function() {
alert('gonderilecek');
},
afterSend: function() {
alert('gonderildi');
},
complete: function(xhr, status) {
if (status == 'success')
alert('success' + $.httpData(xhr));
}
}
and this is my webservice method:
[WebMethod]
public DataTable Hello(string _sTcKimlikNo, int _iKlinikKodu, byte _bAy, int _iYil)
{
DataTable dt = new DataTable();
dt.Columns.Add("ad");
DataRow rw = dt.NewRow();
rw[0] = _sTcKimlikNo + " " + _iKlinikKodu + " " + _bAy + " " + _iYil;
return dt;
}
How can i see datatable from webservice method?
Thanks in advance.
No Serialization problem, just name your datatable and that will solve the problem.
public DataTable LineChrt() {
string query = "select m.class,sum(m.plannedvisits)" +
"plannedvisits,sum(m.actualvisits) actualvisits from vw_MTD_TgtVsAct_Calls1 m " +
"where 1=1 and m.class in ('A','B','C') and m.month = 6 " +
"group by m.class";
string constr = System.Configuration
.ConfigurationSettings.AppSettings["PocketDCR"];
DataTable data = new DataTable();
SqlDataAdapter LCData = new SqlDataAdapter(query,constr);
LCData.Fill(data);
data.TableName = "ChartData";
return data;
}
I don't think you can return a DataTable from a web service due to serialisation problems. This Microsoft article suggests returning a DataSet instead:
Problems using an XML Web service that returns a DataTable

Resources