Save Web Service method name is not valid - asp.net

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

Related

Web API to query SQL Server and return result is not working as expected

I am trying to connect to SQL Server from the Web API and return a result set as JSON. But my code shown here is not working as expected. I am trying to return the entire query response as a JSON:
[HttpGet]
public HttpResponseMessage Getdetails(string ROOM)
{
string commandText = "SELECT * from [TDB].[dbo].[results_vw] where ROOM = #ROOM_Data";
string connStr = ConfigurationManager.ConnectionStrings["TDBConnection"].ConnectionString;
var jsonResult = new StringBuilder();
using (SqlConnection connection = new SqlConnection(connStr))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("#ROOM_Data", SqlDbType.VarChar);
command.Parameters["#ROOM_Data"].Value = ROOM;
connection.Open();
var reader = command.ExecuteReader();
if (!reader.HasRows)
{
jsonResult.Append("[]");
}
else
{
while (reader.Read())
{
jsonResult.Append(reader.GetValue(0).ToString());
}
}
var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
response.Content = new StringContent(jsonResult.ToString());
connection.Close();
return response;
}
}
This code returns this result:
333838362692368203368203368203362692368203359544362692368203362692368203362692368203368203
Where I am expecting the JSON as
{"data":
[
{"R_ID":"368203","ROOM":"K2"},
{"R_ID":"368203","ROOM":"K2"}
]}
Now I created a model class called DatabaseResult to store the response but I am not sure how I can store the result in to the model class in the controller
public class DatabaseResult
{
public int r_id { get; set; }
public string room { get; set; }
}
The current result is because you are only return the the value from the first column of each row and adding it to the string builder.
Create a new instance of the model and populate it using the values from the reader for each row.
[HttpGet]
public IHttpActionResult Getdetails(string ROOM) {
string commandText = "SELECT * from [TDB].[dbo].[results_vw] where ROOM = #ROOM_Data";
string connStr = ConfigurationManager.ConnectionStrings["TDBConnection"].ConnectionString;
var jsonResult = new StringBuilder();
using (SqlConnection connection = new SqlConnection(connStr)) {
using (SqlCommand command = new SqlCommand(commandText, connection)) {
command.Parameters.Add("#ROOM_Data", SqlDbType.VarChar);
command.Parameters["#ROOM_Data"].Value = ROOM;
connection.Open();
List<DatabaseResult> records = new List<DatabaseResult>();
using (var reader = command.ExecuteReader()) {
while (reader.Read()) {
var row = new DatabaseResult {
r_id = (int)reader["r_id"],
room = (string)reader["room"],
//...other properties.
};
records.Add(row);
}
return Ok(records);
}
}
}
}
The above uses the column names as the indexer to get the values from the reader.

Chnage format return of DotNet

I created web API using dotNet. It work but i got a little problem.
This is my controller
WaybillDataAccessLayer objway = new WaybillDataAccessLayer();
public IEnumerable<Waybill> Get(string id_wb)
{
List<Waybill> lstWaybill = new List<Waybill>();
lstWaybill = objway.GetWaybill(id_wb).ToList();
return lstWaybill;
}
and my Models(WaybillDataAccessLayer)
public IEnumerable<Waybill> GetWaybill(String id_wb)
{
List<Waybill> lswaybill = new List<Waybill>();
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("spGetWaybill", con); //Stored procedure on database
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#waybill", id_wb);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read()) //foreach
{
Waybill wb = new Waybill();
wb.waybill = rdr["waybill"].ToString();
wb.deskripsi = rdr["deskripsi"].ToString();
wb.tanggal = rdr["tanggal"].ToString();
wb.pengirim = rdr["pengirim"].ToString();
wb.lokasi = rdr["lokasi"].ToString();
wb.penerima = rdr["penerima"].ToString();
lswaybill.Add(wb);
}
con.Close();
}
return lswaybill;
}
when i run this API,the output will be like this
[
{
"waybill": "00000093",
"deskripsi": "SPARE PARTS",
"tanggal": "19990727",
"pengirim": "JIEP",
"lokasi": "HO",
"penerima": "JKHO"
}
]
My Question is
how to remove that [] ?
how to add another information like
{
"status" : "sucess",
"data" { }
}
Thankyou for your help.
You're returning a list of WayBill objects. If you don't want the resulting JSON to be an array, then you need to just return a single WayBill, not a List. And if you want to wrap that in more data, then create a type to represent that information, populate an instance of it, and return it.
Since you're retrieving these objects by ID, I'm assuming there should be only one WayBill for any given ID. Thus you can simplify your data access layer.
public Waybill GetWaybill(String id_wb)
{
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand("spGetWaybill", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#waybill", id_wb);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
rdr.Read();
Waybill wb = new Waybill();
wb.waybill = rdr["waybill"].ToString();
wb.deskripsi = rdr["deskripsi"].ToString();
wb.tanggal = rdr["tanggal"].ToString();
wb.pengirim = rdr["pengirim"].ToString();
wb.lokasi = rdr["lokasi"].ToString();
wb.penerima = rdr["penerima"].ToString();
return wb;
}
}
And add the type to wrap your response:
class GetWayBillResponse()
{
public string Status { get; set;}
public WayBill WayBill { get; set; }
}
Note that adding a status here isn't really all that helpful if you're seeing the object, you can assume it was successful. Also, the API would have responded with an HTTP 200 OK status code. So it's really superfluous.
Now your controller becomes:
WaybillDataAccessLayer objway = new WaybillDataAccessLayer();
public GetWayBillResponse Get(string id_wb)
{
GetWayBillResponse response = new GetWayBillResponse();
response.Status = "Success";
response.WayBill = objway.GetWaybill(id_wb);
return response;
}
Note that you can simplify your data access even further. You're manually assigning the result columns to the WayBill object. That's repetitive and boring. If you use an Object Relational Mapper such as Dapper, you can remove a lot of that boiler plate code.
Here's what it'd look like using Dapper:
public Waybill GetWaybill(String id_wb)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
return con.QuerySingle<WayBill>("spGetWaybill", new { waybill = id_web }, commandType: CommandType.StoredProcedure);
}
}

Getting a JSON string response from web method

In my web application there is a WCF web service. In the following method
public string GetPolicyDetails(GetPolicyDetails_ML ml)
{
var strFileName = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"log.xml");
DataTable dt = new DataTable();
DataSet ds = new DataSet();
try
{
con = new SqlConnection(connectionString);
con.Open();
cmd = new SqlCommand("sp_GetPolicyDetails", con) { CommandType = CommandType.StoredProcedure };
cmd.Parameters.AddWithValue("#policy_id", ml.policyID);
adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
string json = JsonConvert.SerializeObject(dt,Formatting.Indented);
return json;
}
catch (SqlException ex)
{
return "fail";
}
finally
{
con.Close();
con.Dispose();
}
}
will return a json string inWCF Test Client. I need to access this method from my tab application. The code i used is
ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
var ds = await client.GetPolicyInfoAsync(Convert.ToInt16(txtPolicyNumber.Text));
This will get the response in to the #var ds#. My question is what is the type of this var ds and how to get the Json data out of this variable ds. Thanks in advance.

Ajax to Asmx request works only on localhost

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)

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.

Resources