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
}
Related
I have a jquery ajax script like following
$.ajax({
type: "POST",
url: "Main/receive", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ 'p':$("#txtname").val() }),
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
// Or if you are returning something
},
error: function (result) {
alert('Oh no zzzz:('+result.responseText);
}
});
And I am calling to Controller action method. The data is sending to the controller's action method and I am also receiving data from the controller. But the data that I am receiving is inside the error function of jquery ajax.
I want it to be inside the success function.
Why my success function is not getting called.
Following is my controller's action method,
[HttpPost]
public string receive(string p)
{
ViewBag.name = p;
return p;
}
The reason for the error is that you have specified that the returned data type be json (in the line dataType: "json",) but you method returns text. You have 2 options.
Change the controller method to return json using return Json(p);
Change the ajax option to dataType: "text", or just omit it
However you can improve your script as noted below
$.ajax({
type: "POST",
url: '#Url.Action("receive", "Main")', // don't hardcode url's
data: { p: $("#txtname").val() }, // no need to stringify (delete the contentType: option)
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no zzzz:('+result.responseText);
}
});
or even simpler
$.post('#Url.Action("receive", "Main")', { p: $("#txtname").val() }, function(result) {
alert('Yay! It worked!');
}).fail(function(result) {
alert('Oh no zzzz:('+result.responseText);
});
Notes: You should always use #Url.Action() to generate the correct urls, and it is not necessary in this case to stringify the data (but you need to remove the contentType: line so it used the default application/x-www-form-urlencoded; charset=UTF-8)
In addition, this is not strictly a POST (your not changing data on the server - but I assume this is just for testing). And there is no point in the line ViewBag.name = p; - it does nothing in your context, and as soon as you return from the method, ViewBag is lost anyway.
try to change your controller code as follows
[HttpPost]
public ActionResult List(string p)
{
ViewBag.name = p;
return Json(ViewBag);
}
Your controller method should look like this:
[HttpPost]
public ActionResult receive(string p)
{
return Json(p);
}
I make a total of four Ajax calls in my .NET application. Three of them work without a hitch except the last one.
Note: I HAVE to use .aspx for these calls and not mypage.aspx/mymethod because of our architectural constraints.
Ajax call that works:
$.ajax({
type: "POST",
url: "myaddress/GenerateOpinionHTML.aspx",
data: JSON.stringify({ id: featureId, pageNumber: pageNumberIndex }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
SOME PROCESSING (IT WORKS)
},
error: function (xhr, status, error) {
var err = xhr.responseText;
console.log(err);
}
});
and
[WebMethod]
public static string GenerateOpinionHTML(int id, int pageNumber)
{
// ...
}
Ajax call that does not work:
console.log("SUBMITOPINIONCLICK");
var param = " ";
$.ajax({
type: "POST",
url: "myaddress/SaveOpinion.aspx",
data: JSON.stringify({ parameter: param}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log("SAVE OPINION SUCCESSFUL");
console.log(msg.d);
CloseLB('GiveOpinionLB');
},
error: function (xhr, status, error) {
var err = xhr.responseText;
console.log("ERROR " + "STATUS: " + status);
}
});
and
[WebMethod]
public static string SaveOpinion(string parameter)
{
// ...
}
The web method SaveOpinion is never called according to the logs. Do you have any ideas or suggestions? I tried adding parameters, without parameters, checking my web.config file (though I shouldn't have since the other calls work)...
The error I get on the browser console is a "parseerror". I'm certain I wouldn't be getting an error if the method was called.
I think your URL should be like
url: "Your FolderName/PageName/Function Name",
Like
url: "myaddress/SaveOpinion.aspx/SaveOpinion"
but in your code this is different so that please check.
Have you checked if method SaveOption return something to the client?
If you specify dataType as json, you should return (at least): {}
Ok so we "solved" it. We just found a very dirty band-aid workaround that works.
We made a custom handler (.ashx) that we defined in our architecture as a SaveOpinion.aspx page.
We then called this custom handler page with jQuery and voilĂ it works, we had to obviously pass all necessary parameters manually, ie. fetching all values from textBoxes etc with jQuery and not from the context as we did before.
Since this is run in some sort of thread (I don't really know the details) we had to configure it so that it simulates the same user authentification.
Anyway I hope this provides some measure of guidance for those with this kind of obscure problems.
I have used the JavaScript code to call a method in the c# class (method provided in code). When is does a post back I get an error 500, I would like to know how I can fix this so that I call the method.
JavaScript to call c# class method
$.ajax({
type: "post",
url: "TestChapter.aspx/timeFinished",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
//
}
});
Method in C# class testchapter.aspx:
[System.Web.Services.WebMethod]
public void timeFinished() {
// my code is here
}
Try this method in C# class testchapter.aspx, it might work:
[System.Web.Services.WebMethod]
public static void timeFinished() {
// my code is here
}
Have a look at this post
One thing is that you certainly missed the / char in your ajax method url, it should be:
url: "/TestChapter.aspx/timeFinished",
The other thing is that you should log the error to the console, it's easier that way:
$.ajax({
type: "post",
url: "/TestChapter.aspx/timeFinished",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// do something
},
error: function (data) { // handle your error loging in here
var errorDetails = data.responseText.replace("{", "").split(',');
var errorMessage = "";
for (var i = 0; i < errorDetails.length; i++) {
if (errorDetails[i].split(':')[0] == "\"Message\"") {
errorMessage = errorDetails[i].split(':')[1];
}
}
alert("Error:" + errorMessage);
});
It will write all errors in the debugger console, it's a lot easier to find errors.
I'm using AJAX to populate some cascading combo box as shown in the next image:
When an option is selected in the combo box, it should populate the "Municipio" combo box, to do such a thing I invoke a method using AJAX called CargarCombos(int intAccion, string strCodigo), this method receives the next information:
But the problem resides when receiving the response from the AJAX method, it seems it's not invoking the method mentioned before and to top it all it just responds the same HTML source code that the page contains, has seen here:
If you guys can help me I would be totally grateful. Thanks.
EDIT:
Following the suggestions I'm adding the AJAX command and the WEBMethod:
AJAX:
$.ajax({
type: "POST",
url: pageUrl + '/CargarCombos',
data: '{intAccion: ' + $Accion + ', strCodigo: ' + JSON.stringify($ComboBox.val()) + ' }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
PopularControl(response.d, $control);
},
failure: function(response) {
alert(response.d);
}
});
WEBMEthod:
[WebMethod()]
public static ArrayList CargarCombos(int intAccion, string strCodigo)
{
ArrayList list = new ArrayList();
////LLamo a las variables necesarias.
BLL.cDirecciones DireccionesDAL = new BLL.cDirecciones();
Util.cFuncion oUtil = new Util.cFuncion();
DataSet oDataCombos = new DataSet();
oDataCombos = DireccionesDAL.CargarCombos(intAccion, strCodigo);
if (oDataCombos.Tables[0].Rows.Count > 0)
{
foreach (DataRow row in oDataCombos.Tables[0].Rows)
{
list.Add(new ListItem(row.ItemArray[1].ToString(), row.ItemArray[0].ToString()));
}
}
return list;
}
From the screenshots, it seems you're using WebForms. If that's the case, is the method you are posting to instance or static? Because if it's not static, or the method isn't marked with the WebMethod attribute, this will happen. That's because your ajax request is just treated as a normal full postback.
e.g it should look like
[WebMethod]
//assuming MyModel is the name of your model class to send back to the client.
public static MyModel CargarCombos(int intAccion, string strCodigo)
{
//whatever it is you do here
}
If you're calling the WebMethod via JQuery, make sure that you're setting the content type to JSON e.g.
$.ajax({
type: "POST",
url: "Pendientes.aspx/CargarCombos",
data: "{intAccion:1, strCodigo:'BAR'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
}
});
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.