Error calling web method from jQuery - c#

I am calling a WebMethod from jQuery doing the following:
function WebMethod(fn, paramArray, successFn, errorFn) {
var paramList = {};
if (paramArray.length > 0) {
for (var i = 0; i < paramArray.length; i += 2) {
paramList[paramArray[i]] = paramArray[i + 1];
}
}
var params = $.toJSON(paramList);
$.ajax({
type: 'POST',
url: '../../PricingEngine/ContractView.aspx' + '/' + fn,
contentType: 'application/json; charset=utf-8',
data: params,
dataType: 'json',
success: successFn,
error: function(xhr, status, error) {
// Display a generic error for now.
alert("AJAX Error!");
}
});
}
// Used returned object to populate every field
function updateTextFields(result) {
//do some processing here
}
function failed(result) {
alert('failed');
}
// EVENTS
// ------------------------------------------------------------
$(".editableField").keydown(function(e) {
WebMethod('PriceContract',
[
'AQ', aq.val(),
'SOQ', soq.val()
], updateTextFields, failed);
});
The JSON string after the .toJSON has been called:
{"AQ":"140000","SOQ":"1169"}
The C# method
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static ContractsListPricing PriceContract(string AQ, string SOQ)
{
ContractsListPricing clp = new ContractsListPricing();
clp.Aq = 1;
clp.Soq = 2;
return clp;
}
This is returning the following error:
Invalid JSON: (Followed by the complete HTML of the current page).
Please take no notice of the logic in the C# as this isn't implemented yet. I am using the jquery-json plugin to parse the JSON.
Thanks

Ive run a demo of your code and got it working fine. Have you checked that you have the ScriptModule Handler set correctly in your web.config?

You're sure the exact url is '../../PricingEngine/ContractView.aspx' + '/' + fn ?
Because ContractView.aspx IS your current webpage

Related

ASPNET. - Reponse code 500 when doing Ajax call produces

i have write small application base aspnet with ajax
and i have function ajax look like that
//ajax code
function currentAccountApiToken(userId){
data = JSON.stringify({
"accountID": userId
})
$.ajax({
type: 'POST',
async: false,
url: '/Configurate/controller.aspx/getListApiKey',
data:data,
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (result){
var data = JSON.parse(result.d);
console.log(data.result);
var isExec1 = (data.result[0].isExecute) == 1 ? true : false;
console.log(isExec1);
$('label#apiTokenOne').empty().append(data.result[0].apiToken)
toggleswitch(isExec1,'');
//parse data to element
$('label#apiTokenTwo').empty().append(data.result[1].apiToken)
var isExec2 = (data.result[1].isExecute) == 1 ? true : false;
},
error: (error) => {
console.log(JSON.stringify(error));
}
});
// c# code
//get list profile
[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string get_list_profiles_user(string _account_id)
{
var temp = new Entity.DBEntity.tblProfileUser();
temp._account_id = _account_id;
string _query_string = temp.get_profile_name();
List<Entity.DBEntity.tblProfileUser> _list_profiles = Configurate.sqlBuilder.get_list_profiles(_query_string, Configurate.DBConnection._mysqlcon);
return new JavaScriptSerializer().Serialize(new
{
_list_profiles
});
}
however, when i running code, the return http code 500 with error
jquery-3.3.1.js:9600 POST
http://xxx.xxx.xxx.xxx:88/Configurate/controller.aspx/get_list_profiles_user
profile.js:290 {"readyState":4,"responseText":"{\"Message\":\"There
was an error processing the
request.\",\"StackTrace\":\"\",\"ExceptionType\":\"\"}","responseJSON":{"Message":"There
was an error processing the
request.","StackTrace":"","ExceptionType":""},"status":500,"statusText":"Internal
Server Error"}
so please help me,
thanks !

Ajax call always returning error

I'm having trouble with calling a WebMethod with Jquery.
function runQuery(e) {
var search = $(e).val();
var csKind;
if ($('#rbLP').is(':checked'))
csKind = 1;
else
csKind = 0;
var params = {
url: 'addEditProduct.ascx/AutoComplete_Press',
method: 'post',
contentType: 'application/json',
data: JSON.stringify(search),
dataType: 'json',
success: function(data) {
alert(1);
},
error: function(data) {
alert(2);
}
};
$.ajax(params);
}
[WebMethod]
public static void AutoComplete_Press(string searchClause, int csKind)
{
int searchType = 0; //ЕГН
Regex regex = new Regex("^[0-9]+$");
if (!regex.IsMatch(searchClause))
searchType = 1;
string clients = laboratory.getClients2(searchType, searchClause, csKind);
}
How can I diagnose the problem, I've never used ajax before and I'm at a loss.
The problem I can see here is your passing arguments:
data: JSON.stringify(search),
you are missing csKind, maybe change this line to
data: "{searchClause: '" + search + "',csKind: '" + csKind + "'}",
And change your method to :
public static void AutoComplete_Press(string searchClause, string csKind)
The url seems to be wrong if you ask me. Open up your console in the browser and see what it says, it will be throwing cant connect/connection refused error. Also open network in the browser and you can check what http response you are getting. This will help u start up diagnosing the problem.

Passing String into an API method with a Route Attribute

I have a method on an API Controller where I've set the route in an attribute, but I don't seem to be able to pass a string into this. When I try to hit this with an Ajax Request from the browser the console shows the following error:
BAD REQUEST - The request could not be processed by the server due to
invalid syntax.
The string I'm passing over is huge, but unfortunately is the only way I can import the data into the legacy application I'm working with. The test URL I'm using is (brace yourselves):
http://localhost:50915/api/job/import/ALMIG&sup3123456&sup32%20DAY%20ECONOMY&sup320170720&sup320170721&sup30&sup3&sup3&sup3&sup322&sup3Lara%20Croft%20Way&sup3Derby&sup3&sup3&sup3DE23%206GB&sup3Stuff&sup310&sup31&sup30&sup325&sup30&sup3&sup31%7CI%20Great%20Danger&sup30&sup30&sup30&sup3&sup3&sup30&sup3true&sup30&sup3&sup3&sup3&sup3&sup3&sup3&sup31&sup30&sup30&sup316&sup3Baden%20Road&sup3Stoke-on-Trent&sup3&sup3&sup3ST6%201SA&sup3&sup30&sup30&sup30&sup3&sup3&sup3&sup30&sup30&sup30&sup30&sup3&sup30&sup31&sup30&sup3&sup3&sup3&sup3&sup3&sup3&sup3&sup3&sup3&sup3&sup3Liane&sup307730044916&sup3Lara&sup307730044916&sup30&sup3d2f0acf7-50e1-4a53-96ce-4fffd00b1a96&sup30
And the method is defined as below, the code inside is irrelevant as I put a break point on the start of the method which is never hit:
[System.Web.Http.HttpPost]
[System.Web.Http.Route("api/job/import")]
public int TmsImport([FromBody]string import)
{
// do something...
}
Edit: Added Ajax Request
job.confirmBookings = function () {
// TMS Import
job.toConfirmRow.filter(function(obj) {
var jobRow = obj;
var strArray = [];
for (var prop in jobRow) {
if (jobRow.hasOwnProperty(prop)) {
strArray.push(jobRow[prop]);
}
}
var joinedStr = strArray.join(job.seperator);
$.ajax({
type: "POST",
crossDomain: true,
data: joinedStr,
url: job.tmsString,
contentType: "application/json;charset=utf-8",
success: function (data, status, xhr) {
console.log("TMS ID: " + data + " | " + status);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
});
First format the route template correctly
[HttpPost]
[Route("api/job/import")] //Matches POST api/job/import
public int TmsImport([FromBody]string import) {
// do something...
}
Also you should post the data in the body of the request. If the payload is large then you do not want that in the URL

How to obtain checked checkbox values on the serverside in c# from an ajax Http POST using web forms (not MVC)?

Here's my ajax call:
$(function () {
$("#chkFilter").on("click", "input", function (e)
{
var filterCheckboxes = new Array();
$("#chkFilter").find("input:checked").each(function () {
//console.log($(this).val()); //works fine
filterCheckboxes.push($(this).prop("name") + "=" + $(this).val());
console.log($(this).prop("name") + "=" + $(this).val());
//var filterCheckboxes = new Array();
//for (var i = 0; i < e.length; i++) {
// if (e[i].checked)
// filterCheckboxes.push(e[i].value);
//}
});
console.log("calling ajax");
$.ajax({
url: "/tools/oppy/Default",
type: "POST",
dataType: "json",
data: { filterValues: filterCheckboxes }, // using the parameter name
success: function (result) {
if (result.success) {
}
else {
}
}
});
});
});
And my server side code:
public partial class tools_oppy_Default : System.Web.UI.Page
{
...
protected void Page_Load(object sender, EventArgs e)
{
if (Request.HttpMethod == "POST")
{
string checkedBoxes = Request["filterValues"];
testLabel.Text = checkedBoxes;
}
I'm just trying to obtain the post URL with the appropriate checked values so I can parse it on the server. However, I'm having trouble obtaining the URL. The string checkedBoxes is supposed to hold a query string like name=value&name=value&name.... but when I test it, the testLabel doesn't show anything. I'm using web forms app, not MVC. Also, I'm new to ajax and their behavior. Thanks.
First, I assume that the url in you JQuery call is valid as there is not aspx extension their.
Second, It looks like what you need to do is create a web method and call it from JQuery for example the following is a web method that accept string
[WebMethod]
public static string GetData(String input)
{
return DateTime.Now.ToString();
}
and you can call it using the same way with your current code just update the url parameter to include the method name
url: "PageName.aspx/MethodName",
for more details about web methods and their union with JQuery please check this article
Edited The following is complete sample
The web method should look like the following one
[WebMethod]
public static string GetData(string filterValues)
{
return filterValues; //This should be updated to return whatever value you need
}
The client side part of calling the web method should look like the following
$.ajax({
url: "/Default/GetData",
type: "POST",
contentType: "application/json; charset=utf-8", //I have added this as "contentType" parameter represents the type of data inside the request meanwhile the "data" parameter describes the data inside the response
data: "{ filterValues:\"" + filterCheckboxes + "\"}", //Note that I have updated the string here also set the name of the parameter similar to the input of the webmethod
dataType: "json",
success: function (result) {
alert(result.d);//You should access the data using the ".d"
}
});
One last thing, If you are using asp.net permanent routing the above code will not work and you should disable it by updating the file "App_Code/RouteConfig.cs" From
settings.AutoRedirectMode = RedirectMode.Permanent;
To
settings.AutoRedirectMode = RedirectMode.Off;
And remember to clear browser cache after the above update

How to call webmethod in Asp.net C#

I want to call a web method in asp.net c# application using the following code
Jquery:
jQuery.ajax({
url: 'AddToCart.aspx/AddTo_Cart',
type: "POST",
data: "{'quantity' : " + total_qty + ",'itemId':" + itemId + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
alert("Start!!! ");
},
success: function (data) {
alert("a");
},
failure: function (msg) { alert("Sorry!!! "); }
});
C# Code:
[System.Web.Services.WebMethod]
public static string AddTo_Cart(int quantity, int itemId)
{
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Add";
}
But it always call page_load. How can i fix it?
There are quite a few elements of the $.Ajax() that can cause issues if they are not defined correctly. I would suggest rewritting your javascript in its most basic form, you will most likely find that it works fine.
Script example:
$.ajax({
type: "POST",
url: '/Default.aspx/TestMethod',
data: '{message: "HAI" }',
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
},
failure: function (response) {
alert(response.d);
}
});
WebMethod example:
[WebMethod]
public static string TestMethod(string message)
{
return "The message" + message;
}
This is a bit late, but I just stumbled on this problem, trying to resolve my own problem of this kind. I then realized that I had this line in the ajax post wrong:
data: "{'quantity' : " + total_qty + ",'itemId':" + itemId + "}",
It should be:
data: "{quantity : '" + total_qty + "',itemId: '" + itemId + "'}",
As well as the WebMethod to:
public static string AddTo_Cart(string quantity, string itemId)
And this resolved my problem.
Hope it may be of help to someone else as well.
Necro'ing this Question ;)
You need to change the data being sent as Stringified JSON, that way you can modularize the Ajax call into a single supportable function.
First Step: Extract data construction
/***
* This helper is used to call WebMethods from the page WebMethods.aspx
*
* #method - String value; the name of the Web Method to execute
* #data - JSON Object; the JSON structure data to pass, it will be Stringified
* before sending
* #beforeSend - Function(xhr, sett)
* #success - Function(data, status, xhr)
* #error - Function(xhr, status, err)
*/
function AddToCartAjax(method, data, beforeSend, success, error) {
$.ajax({
url: 'AddToCart.aspx/', + method,
data: JSON.stringify(data),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
beforeSend: beforeSend,
success: success,
error: error
})
}
Second Step: Generalize WebMethod
[WebMethod]
public static string AddTo_Cart ( object items ) {
var js = new JavaScriptSerializer();
var json = js.ConvertToType<Dictionary<string , int>>( items );
SpiritsShared.ShoppingCart.AddItem(json["itemId"], json["quantity"]);
return "Add";
}
Third Step: Call it where you need it
This can be called just about anywhere, JS-file, HTML-file, or Server-side construction.
var items = { "quantity": total_qty, "itemId": itemId };
AddToCartAjax("AddTo_Cart", items,
function (xhr, sett) { // #beforeSend
alert("Start!!!");
}, function (data, status, xhr) { // #success
alert("a");
}, function(xhr, status, err){ // #error
alert("Sorry!!!");
});
One problem here is that your method expects int values while you are passing string from ajax call. Try to change it to string and parse inside the webmethod if necessary :
[System.Web.Services.WebMethod]
public static string AddTo_Cart(string quantity, string itemId)
{
//parse parameters here
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Add";
}
Edit : or Pass int parameters from ajax call.
I'm not sure why that isn't working, It works fine on my test. But here is an alternative technique that might help.
Instead of calling the method in the AJAX url, just use the page .aspx url, and add the method as a parameter in the data object. Then when it calls page_load, your data will be in the Request.Form variable.
jQuery
jQuery.ajax({
url: 'AddToCart.aspx',
type: "POST",
data: {
method: 'AddTo_Cart', quantity: total_qty, itemId: itemId
},
dataType: "json",
beforeSend: function () {
alert("Start!!! ");
},
success: function (data) {
alert("a");
},
failure: function (msg) { alert("Sorry!!! "); }
});
C# Page Load:
if (!Page.IsPostBack)
{
if (Request.Form["method"] == "AddTo_Cart")
{
int q, id;
int.TryParse(Request.Form["quantity"], out q);
int.TryParse(Request.Form["itemId"], out id);
AddTo_Cart(q,id);
}
}
The problem is at [System.Web.Services.WebMethod], add [WebMethod(EnableSession = false)] and you could get rid of page life cycle, by default EnableSession is true in Page and making page to come in life though life cycle events..
Please refer below page for more details
http://msdn.microsoft.com/en-us/library/system.web.configuration.pagessection.enablesessionstate.aspx
you need to JSON.stringify the data parameter before sending it.
Here is your answer.
use
jquery.json-2.2.min.js
and
jquery-1.8.3.min.js
Javascript :
function CallAddToCart(eitemId, equantity) {
var itemId = Number(eitemId);
var quantity = equantity;
var dataValue = "{itemId:'" + itemId+ "', quantity :'"+ quantity "'}" ;
$.ajax({
url: "AddToCart.aspx/AddTo_Cart",
type: "POST",
dataType: "json",
data: dataValue,
contentType: "application/json; charset=utf-8",
success: function (msg) {
alert("Success");
},
error: function () { alert(arguments[2]); }
});
}
and your C# web method should be
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string AddTo_Cart(int itemId, string quantity)
{
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Item Added Successfully";
}
From any of the button click or any other html control event you can call to the javascript method with the parameter which in turn calls to the webmethod to get the value in json format.

Categories

Resources