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);
}
});
Related
I'm posting data with ajax and it's successfully posted. At the controller side I'm filling a ViewBag with data posted but i'm having a problem getting data from ViewBag.
Here's Ajax Code:
$.ajax({
type: "POST",
url: '../Home/getExistUsersFromJSON',
data: JSON.stringify({ jsonString: JSON.stringify(array) }),
traditional: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function () {
// Alert that it was succesful!
var jsonList = '#Html.Raw(Json.Convert(ViewBag.newUsers))';
var jsList = JSON.parse(jsonList);
bootbox.dialog({
message: jsList,
title: "Utilisateurs",
buttons: {
success: {
label: "Success!",
className: "btn-success"
}
}
});
}
});
And this is the controller side
[ActionName("getExistUsersFromJSON")]
public void getExistUsersFromJSON(string jsonString)
{
IList<newUser> ctm =
new JavaScriptSerializer().Deserialize<IList<newUser>>(jsonString);
ViewBag.newUsers = ctm.ToList();
}
ViewBag is just an object that gets passed to the view when you render the page.
It doesn't make any sense to use that with AJAX; your server-side Razor code runs on initial server render only.
You need to server JSON as the response (using Json()).
I have an aspx page. I want to call the ASP.NET method via jquery. I have implemented the code but the problem is that I am getting the HTML of whole page rather than getting the returned string from ASP method. I need some assistance.
Here is my code:
[WebMethod]
public string PopulateData(string coursename)
{
return "called";
}
and here is the jquery method:
var subject = 'database';
$.ajax({
type: "POST",
url: "CourseDetail.aspx/PopulateData",
data: "{coursename:'" + subject + "'}",
success: function (msg) {
// Do something interesting here.
alert('result : ' + msg);
}
Add in the contentType and dataType.
var subject = 'database';
$.ajax({
type: "POST",
dataType: "text",
contentType: "application/json; charset=utf-8",
url: "CourseDetail.aspx/PopulateData",
data: "{coursename:'" + subject + "'}",
success: function (msg) {
// Do something interesting here.
alert('result : ' + msg);
}
contentType is the header sent to the server, specifying a particular format.
Example: I'm sending json or XML
dataType is telling jQuery what kind of response to expect.
Expecting JSON, or XML, or HTML, etc....
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
}
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.
Im trying to bind an html select and i wrote a webmethod for that, which returns a list. How can i use this return value to bind my select control using jquery.... ? I'm stuck... The code is appended herewith :
function columnDropdownScript() {
var reqTableNameParameter = "Designation"; //$('#ddlTableNames').text;
var requestTableParameters = '{' +
'selTableName:"' + reqTableNameParameter + '"}';
// Configure AJAX call to server
$.ajax({
type: "POST",
url: "Webtop.aspx/FillColumnDropdown",
data: requestTableParameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: DisplayColumnNames, //Event that'll be fired on Success
error: DisplayError //Event that'll be fired on Error
});
}
function DisplayColumnNames(serverResponse) {
$("#ddlColumnNames").get(0).options.length = 0;
$("#ddlColumnNames").get(0).options[0] = new Option("Select", "-1");
$.each(serverResponse.d, function(index, item) {
$("#ddlColumnNames").get(0).options[$("#ddlColumnNames").get(0).options.length] = new Option(item.Display, item.Value);
});
alert('Check Column DropDown');
}
[WebMethod]
public static List<string> FillColumnDropdown(string selTableName)
{
int x=1;
string selectedTable = selTableName;
List<string> columnsToBind = new List<string>();
foreach (Columns column in Metadata.columnsOfSelectedTables)
{
if (column.TableName.Equals(selectedTable))
{
columnsToBind.Add(column.ColumnName);
}
}
return columnsToBind;
}
// I haven't tested this, but off the top of my head, this should do the trick
// (note, this is appending to the list. you may need to clear if called multiple times)
$.ajax({
type: "POST",
url: "Webtop.aspx/FillColumnDropdown",
data: requestTableParameters,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
for (var i = 0, l = msg.length; i < l; i++) {
$("#the_selectbox").append("<option>" + msg.d[i] + "</option>");
}
},
error: DisplayError //Event that'll be fired on Error
});
Just for curiosity, why did you do a web method for that instead of adding it onload / postback trigger?
And where are you casting your list to json in code behind? Wouldn't it's return type be xml?
Anyway, jQuery objects properties ask for anonymous functions:
$.ajax({
// ...
success:function(serverResponse){
//success code
},
error:function(serverResponse){
//error code
},
});