How to call webmethod in Asp.net C# - 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.

Related

How to call codebehind method from Jquery after autocomplete selection

I have a autocomplete text box as and when the user types the city names are prompted. Once the user selects city name the selected value is retrieved using the following code:
$(document).ready(function() {
$('#txtName').on('change', function() {
$('#selectedItem').html('You selected: ' + this.value);
}).change();
$('#txtName').on('autocompleteselect', function(e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Now I need to pass the selected value and call method in aspx.cs (code-behind) to retrieve further details of selected city.
How can I call a method from JQuery can somebody guide me towards that
You must call ajax in autocompleteselect like this
$('#txtName').on('autocompleteselect', function (e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
$.ajax({url: "aspx.cs",data:{value:ui.item.value}, success: function(result){
//response from server
}});
});
Server Side changes
You need to mark that method with WebMethod attribute to call it from the client side or you need to create a web service.
[WebMethod]
public static yourObject GetCityDetails(string cityId)//name this method as per your needs.
{
//Do whatever you want.
return yourObject; //it can also be in JSON format.
}
Client Side changes
Make an ajax call to the method from the client side.
$('#txtName').on('autocompleteselect', function(e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
$.ajax({
url: "yourpage.aspx/GetCityDetails", //same method name here.
data: { cityId: this.value },
success: function(result) {
//do whatever you want with server side data here.
}
});
});
You Can use Web Method
function GetDetails(cityId) {
$.ajax({
type: "POST",
url: 'Default.aspx/GetDetails',
data: {"cityId":cityId},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log(msg);
},
error: function (e) {
console.log(e);
}
});
}
$(document).ready(function() {
$('#txtName').on('change', function() {
$('#selectedItem').html('You selected: ' + this.value);
}).change();
$('#txtName').on('autocompleteselect', function(e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
GetDetails(ui.item.value);
});
in your aspx page
[WebMethod] //Default.aspx.cs
public static void GetDetails(cityId)
{
//Your Logic
}
Use $.Ajax to send the selected value to the server (code-behind) and get the response:
$('#txtName').on('autocompleteselect', function(e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
$.ajax({
url: "your-page.aspx/GetCityDetails",
data: { Name: this.value },
success: function(result) {
//Process the result from the code-behind.
}
});
});
Your code-behind must have a webmethod named GetCityDetails that accepts the name parameter and returns a city object as JSON.
This is what solved my issue:
The following is the code in jquery part in .aspx
function SetCityName(cityName) {
$.ajax({
type: "POST",
url: 'Default.aspx/GetCityDetails',
data: JSON.stringify({ cityName: cityName }),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("CityName:" + cityName + "\n\nRequest: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result.d);
}
});
}
This is the code in .aspx.cs
[WebMethod]
public static string GetCityDetails(string cityName)
{
MessageBox.Show(cityName);
return "success";
}
The trick part is using the following piece in JQuery. I have tried above alternatives provided but none worked apart from the below piece of code:
data: JSON.stringify({ cityName: cityName }),

ajax not working to call asp.net web method

I am calling asp.net web method in my ajax call. Web method looks like below
[WebMethod()]
public static int DropDownIndexChanged(string selectedText)
{
int a = 5; // This is just to test
return a;
}
And in my ajax call, i am sending selected value in a drop down, having id DropDown, as follows
$.ajax({
type: "POST",
url: "FindFines.aspx/DropDownIndexChanged",
data: { "selectedText":"+$("#DropDown option:selected").text()+"},
success: function (data) {
alert("Success");
}
});
But function is not being called. Please guide me the right way to do it. Thanks.
I think your problem is "+$("#DropDown option:selected").text()+"
var value = $("#DropDown option:selected").text();
$.ajax({
type: "POST",
url: "FindFines.aspx/DropDownIndexChanged",
data: { "selectedText": value },
success: function (data) {
alert("Success");
}
});
Please Change
[WebMethod()]
to
[WebMethod]
and
data: { "selectedText":"+$("#DropDown option:selected").text()+"}
to
data: '{selectedText: "' + $("#DropDown option:selected").text() + '" }'

jquery webmethod call returns whole page html

I have a website www.arabadukkan.com
I have cascading comboboxes at the top (araç türü->marka->model etc)
I am calling a webmethod to return the results but the result is the html of entire page.
This code works great in my local
WebMethod code :
public static string GetMarkas(string selectedId)
{
var items = Service.DS.GetMarkas().WithCategoryId(selectedId.SayiVer());
string donen = "<option value=''>Tüm Markalar...</option>";
foreach (var item in items) donen += string.Format("<option value='{0}'>{1}</option>", item.id, item.Title);
return donen;
}
I couldnt find any solution. When i look the network tab in chrome i see the GetMarkas response header is "Content-Type:text/html; charset=utf-8"
My script is :
function GetCombo(fromCombo, toCombo, method) {
var veriler = {
selectedId: $(fromCombo).val()
};
$(toCombo).find('option').remove().end().append("<option value='0'>Yükleniyor...</option>");
$.ajax({
type: "POST",
url: ResolveUrl('~/wm.aspx/') + method,
data: $.toJSON(veriler),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$(toCombo).find('option').remove().end().append(msg.d);
$(toCombo).trigger("change");
},
error: function (msg, x, error) {
alert("Hata Oluştu." + error);
}
});
}
Try below code I guess u don't require json here..
function GetCombo(fromCombo, toCombo, method) {
var veriler = {
selectedId: $(fromCombo).val()
};
$(toCombo).find('option').remove().end().append("<option value='0'>Yükleniyor...</option>");
$.ajax({
type: "POST",
url: ResolveUrl('~/wm.aspx/') + method,
data: { selectedId : veriler},
dataType: 'html',
success: function (msg) {
$(toCombo).find('option').remove().end().append(msg.d);
$(toCombo).trigger("change");
},
error: function (msg, x, error) {
alert("Hata Oluştu." + error);
}
});
}
You may want to make sure that you've added necessary web.config entries, specifically httpModules section. Please go through this

Calling a c# method trough Ajax without using static methods

I am doing a website where I have to use ajax and was wondering if there is a way to call a method from the server side with out setting the method to static. I researched this but every example I found has the method set as static and was wondering if you could this with using static here is my code
Ajax Code:
function GetAddColour(id, Name) {
var dataValue = { "id": id, "Name": Name }
$.ajax({
url: "AddColour.aspx/btnAddColour",
type: "POST",
dataType: "json",
data: dataValue,
contentType: "application/json; charset=utf-8",
success: function (msg) {
alert("Success");
},
error: function (e) {
alert(JSON.stringify(e));
}
});
}
The C# code:
[WebMethod]
public static void btnAddColour(int id, string Name)
{
//do things to add colour
}
Is there a way to this without static method and also I cannot use update panels.
Using ASP.NET AJAX Page Methods you can access the Session object, so if you store your logged in user name in Session["User"], then you could do something like this:
Code-behind:
[WebMethod(EnableSession = true)]
public static string GetLoggedInUserName()
{
return HttpContext.Current.Session["User"].ToString();
}
Markup:
$.ajax({
url: "AddColour.aspx/GetLoggedInUserName",
type: "POST",
dataType: "json",
data: "{}",
contentType: "application/json; charset=utf-8",
success: function (result) {
if (result.hasOwnProperty("d")) {
// Need to de-reference the JSON via the .d
alert(result.d);
}
else
{
// No .d; no de-reference necessary
alert(result);
}
},
error: function (e) {
alert(JSON.stringify(e));
}
});
Note: The .d syntax was an anti-XSS protection put in by Microsoft in the ASP.NET 3.5 release of ASP.NET AJAX; therefore the check to see if the .d property is there or not.
Assuming you're using web forms rather than ASP.Net MVC, you can create a *.ashx HttpHandler. It's just like a *.aspx page, but much much simpler. Your code-behind just has to implement the IHttpHandler interface (1 method, ProcessRequest() and 1 property IsReusable). If you require access to session state, you'll also need to "implement" (a misnomer, since these are both marker interfaces with nothing to implement) either IReadonlySessionState (read-only access) or IRequiresSessionState (read/write access).
However, you're responsible for pretty much everything from soup to nuts here. You can return JSON, binary image data, whatever your little heart desires.
modify your datavalue to this.
var dataValue = "{id :'" + id + ", Name :'"+ Name "'}" ;
where id and name are two variables which have integer and string value respectively.
Ensure id to be integer, if it is not then change it to Number(id)
Javascript :
function GetAddColour(eid, eName) {
var id = Number(eid);
var Name = eName;
var dataValue = "{id :'" + id + ", Name :'"+ Name "'}" ;
$.ajax({
url: "AddColour.aspx/btnAddColour",
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 void btnAddColour(int id, string Name)
{
// Your code here
}

Ajax post returning error "Not Found"

Im having the following ajax cal in my JS file in Durundal ,
var dataJSON ={ID : "jo"};
self.js = $.ajax({
type: "POST",
dataType: text,
url: "http://localhost:53081/api/File",
data: JSON.stringify(dataJSON),
error: function (xhr, status, error) {
alert(error);
},
success: function (json) {
alert("Data Returned: " + JSON.stringify(json));
}
});
and my REST api is
[HttpPost]
public string upload(string ID)
{
string givenId = ID;
return givenId;
}
but when i call thsi methos im simply getting error alert . what went wrong
update
i have updated my code but now im getting Not found error
Change string to Text:
self.js = $.ajax({
type: "POST",
dataType: **Text**,
url: "url",
data: JSON.stringify(dataJSON),
error: function (xhr, status, error) {
alert(status);
},
success: function (json) {
alert("Data Returned: " + JSON.stringify(json));
}
});
click here for list of datatype and there representation.
You may need to change the name of the method to be PostFile. I had issues getting this to work without having the proper naming convention, even though I had the [HttpPost] attribute at the beginning of the method.
Also: try changing your dataType to "json" and adding the content type:
dataType: "json",
contentType: "application/json"

Categories

Resources