Ajax to Asmx request works only on localhost - asp.net

This is request:
var xCoordinateString = 111;
var yCoordinateString = 111;
$.ajax({
type: "POST",
url: "InsertCoordinates.asmx/Insert",
data: { xCoordinates: xCoordinateString, yCoordinates: yCoordinateString },
success: function (response) {
alert('yes');
},
error: function (data) {
alert('no');
}
});
This is Insert function in webservice:
public void Insert(string xCoordinates, string yCoordinates)
{
string[] xCoords = xCoordinates.Split(',');
string[] yCoords = yCoordinates.Split(',');
//The following is a ZIP operation which allows you to do a foreach loop on two arrays.
var xANDyCoordinates = xCoords.Zip(yCoords, (x, y) => new { xCoord = x, yCoord = y });
foreach (var xy in xANDyCoordinates)
{
SqlConnection connection = new SqlConnection(GetConnectionString());
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd = new SqlCommand("InsertIndividualHeatMapCoordinates", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("xCoord", xy.xCoord));
cmd.Parameters.Add(new SqlParameter("yCoord", xy.yCoord));
cmd.ExecuteNonQuery();
}
}
But, it pushes data only when I access my server using remote desktop connection and open http://localhost:8032/
When using my machine and accessing http://networkname11:8032/ - (Aborted)

Related

Save Web Service method name is not valid

I Create a Form in Asp.net Web App using angular js and I create save Form Data in database functionality using Asmx file But when I click on save Button the error will occure in console
This Error will be occure when i click submit button
This is My StudentService.Asmx file code
public class StudentService : System.Web.Services.WebService
{
[WebMethod]
public void Save(Student emp)
{
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("sp_GetAllEmployee", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "#FirstName",
Value = emp.FirstName
});
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "#LastName",
Value = emp.LastName
});
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "#Gender",
Value = emp.Gender
});
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "#TraningType",
Value = emp.TraningType
});
con.Open();
cmd.ExecuteNonQuery();
}
}
This Is my Angular Js Code
/// <reference path="angular.js" />
var MyApp = angular.module("Test", []).controller("MyController", function ($scope, $http) {
$scope.Save = function () {
$http.post("StudentService.asmx/Save")
.then(function (response) {
$scope.Student = response.data;
});
}
});

jQuery Bootgrid sorting, pagination and search functionality not working

I have a jQuery bootgrid implemented into my ASP.Net application which is filled using a Generic Handler.
I fill the bootgrid using the Generic Handler as follows:
$(function () {
var grid = $("#grid").bootgrid({
ajax: true,
ajaxSettings: {
method: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false
},
url: "/MyHandler.ashx",
rowCount: [10, 50, 75, 100, 200, -1]
});
}
Here's MyHandler.ashx code:
public class RolesHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/json";
context.Response.Write(GetData());
}
public bool IsReusable
{
get
{
return false;
}
}
public string GetData()
{
var result = string.Empty;
var con = new SqlConnection();
var cmd = new SqlCommand();
var dt = new DataTable();
string sSQL = #"SELECT Id, Name
FROM dbo.AspNetRoles;";
try
{
using (var connection = THF.Models.SQLConnectionManager.GetConnection())
{
using (var command = new SqlCommand(sSQL, connection))
{
connection.Open();
command.CommandTimeout = 0;
var da = new SqlDataAdapter(command);
da.Fill(dt);
}
}
var sNumRows = dt.Rows.Count.ToString();
var sDT = JsonConvert.SerializeObject(dt);
result = "{ \"current\": 1, \"rowCount\": 10, \"rows\": " + sDT + ", \"total\": " + sNumRows + " }";
}
catch (Exception ex)
{
}
finally
{
cmd.Dispose();
THF.Models.SQLConnectionManager.CloseConn(con);
}
return result;
}
}
Basically all the important functionality of my bootgrid that worked before I implemented it the ajax way doesn't work anymore. Specifically the ordering, searching and pagination functionality aren't working at all without any errors.
As far as I know from a bit of research. This is because every time a search phrase is made, or a header is clicked (for ordering) etc. The bootgrid performs an ajax call.
Any idea on how to fix the functionality here?
After much work I ended up getting it working and this is the final code result:
public class RolesHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/json";
var current = context.Request.Params["current"];
var rowCount = context.Request.Params["rowCount"];
var orderById = context.Request.Params["sort[Id]"];
var orderByName = context.Request.Params["sort[Name]"];
var searchPhrase = context.Request.Params["searchPhrase"];
var orderBy = "Id";
var orderFrom = "ASC";
if (orderById != null)
{
orderBy = "Id";
orderFrom = orderById;
}
else if (orderByName != null)
{
orderBy = "Name";
orderFrom = orderByName;
}
context.Response.Write(GetData(current, rowCount, orderBy, orderFrom, searchPhrase));
}
public bool IsReusable
{
get
{
return false;
}
}
public string GetData(string current, string rowCount, string orderBy, string orderFrom, string searchPhrase)
{
var result = string.Empty;
var currentNum = Convert.ToInt32(current) - 1;
var temp = 0;
if (!"Id".Equals(orderBy, StringComparison.OrdinalIgnoreCase)
&& !"Name".Equals(orderBy, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException("orderBy is not a valid value");
if (!"desc".Equals(orderFrom, StringComparison.OrdinalIgnoreCase) && !"asc".Equals(orderFrom, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException("orderFrom is not a valid value");
if (!int.TryParse(rowCount, out temp))
throw new ArgumentException("Rowcount is not a valid number");
var dt = new DataTable();
string sSQL = #"SELECT Id, Name
FROM dbo.AspNetRoles
WHERE Id LIKE #searchPhrase
OR Name LIKE #searchPhrase
ORDER BY " + orderBy + " " + orderFrom + #"
OFFSET ((" + currentNum.ToString() + ") * " + rowCount + #") ROWS
FETCH NEXT " + rowCount + " ROWS ONLY;";
using (var connection = THF.Models.SQLConnectionManager.GetConnection())
{
using (var command = new SqlCommand(sSQL, connection))
{
command.Parameters.Add(new SqlParameter("#searchPhrase", "%" + searchPhrase + "%"));
command.Parameters.Add(new SqlParameter("#orderBy", orderBy));
connection.Open();
command.CommandTimeout = 0;
var da = new SqlDataAdapter(command);
da.Fill(dt);
connection.Close();
}
}
var total = string.Empty;
string sSQLTotal = #"SELECT COUNT(*)
FROM dbo.Log
WHERE Id LIKE #searchPhrase
OR Name LIKE #searchPhrase;";
using (var connection = THF.Models.SQLConnectionManager.GetConnection())
{
using (var command = new SqlCommand(sSQLTotal, connection))
{
command.Parameters.Add(new SqlParameter("searchPhrase", "%" + searchPhrase + "%"));
connection.Open();
command.CommandTimeout = 0;
total = command.ExecuteScalar().ToString();
connection.Close();
}
}
var rows = JsonConvert.SerializeObject(dt);
return result = "{ \"current\": " + current + ", \"rowCount\": " + rowCount + ", \"rows\": " + rows + ", \"total\": " + total + " }";
}
}

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;
}

accessing data using ajax page methods directly

I want to access data and show in label ajax page methods but data is not displaying.
PageMethods.GetDataFromDB(OnSucceeded, OnFailed);
//}
function OnSucceeded(result, userContext, methodName) {
var jsonData = eval(result.d);
$get('Label1').innerHTML = jsonData.FirstName;
}
[WebMethod]
public static string GetDataFromDB()
{
System.Collections.Generic.Dictionary<string, string> DictionaryGetPerson = new Dictionary<string, string>();
using (OracleConnection con = new OracleConnection("server=xe; uid=system; pwd=;"))
{
string Command = "Select * from tblSavePerson"; //selecting Top 1 Row in Oracle
OracleCommand cmd = new OracleCommand(Command, con);
con.Open();
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
DictionaryGetPerson.Add("FirstName",dr["FirstName"].ToString());
}
}
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(DictionaryGetPerson).ToString();
}
table has only one row.
Since you have given the tags as jQuery and jQuery Ajax I am deviating a little from the solution.
Do these things
1.Wrap your WebMethod in a try-catch block. try-catch are there for a reason.
[WebMethod]
public static string GetDataFromDB()
{
try
{
System.Collections.Generic.Dictionary<string, string> DictionaryGetPerson = new Dictionary<string, string>();
using (OracleConnection con = new OracleConnection("server=xe; uid=system; pwd=;"))
{
string Command = "Select * from tblSavePerson"; //selecting Top 1 Row in Oracle
OracleCommand cmd = new OracleCommand(Command, con);
con.Open();
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
DictionaryGetPerson.Add("FirstName", dr["FirstName"].ToString());
}
}
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(DictionaryGetPerson).ToString();
}
catch (Exception exception)
{
//Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
throw new Exception(exception.Message);
}
}
Please note that this Dictionary will fail with Duplicate Key error if you have more than one row. If there are no errors lets move to step 2.
2.Do not use PageMethods.GetDataFromDB. It very ancient. Using jQuery one can consume ASP.NET Ajax Page Methods directly. Call Page method like this.
function LoadNames() {
$.ajax({
contentType: "application/json;",
data: "{}",
type: "POST",
url: 'Test1.aspx/GetDataFromDB',
success: function (msg) {
OnSucceeded(msg);
},
error: function (xhr, status, error) {
//alert("error");
//OnFailed(a, b, c);
}
});
}
function OnSucceeded(dict) {
var jsonData = dict.hasOwnProperty("d") ? dict.d : dict;
var json = $.parseJSON(jsonData);
alert(json.FirstName);
}
Also, don't eval(result.d) when we have $.parseJSON in jQuery.
Hope this helps.

Arraylist and webmethod

I have written a web method in ASP.net which it's output is an ArrayList of cities that is read from Sql server database.
this webmethod is called using Jquery in clientside.
but I don't know how to read each item of array list using jquery. for example every city and it's id equivalent.
Below is my Webmethod:
public ArrayList showcity(int s)
{
ArrayList list = new ArrayList();
String strConnString = ConfigurationManager
.ConnectionStrings["ConnectionCS"].ConnectionString;
String strQuery = "select ID, City from tbl_city where stateid=#s";
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#s", s);
cmd.CommandText = strQuery;
cmd.Connection = con;
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
list.Add(new ListItem(
sdr["City"].ToString(),
sdr["ID"].ToString()
));
}
con.Close();
return list;
}
}
and this is my clientside code:
function showcity() {
$.ajax(
{ url: "../AjaxServices/StateCity.asmx/showcity",
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
data: '{s: ' + $('#<%=DpState.ClientID%>').val() + '}',
success: function(data) {
***// what should I write here to access every item separately***
},
error: function() { alert("Error"); }
})
}
If I use alert(data.d) I will get [object][object][object][object],.....
You need to create an actual type and return an array of that type. So create a City class, mark it serializable, build a List<City> in your loop, then return .ToArray(). The return type of your web method should be City[]
Instead of ArrayList being returned, it would be better to return an array with two dimension.
I found a solution myself so I share it here, just be careful about Value and Text they're case sensitive
success: function(data) {
$.each(data.d, function() {
alert(this['Value'] + ':' + this['Text']);
})
}

Resources