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() + '" }'
Related
I am calling jquery function on dropdown value change jquery method is ,
function MyFunction() {
alert($('#DDlSurvey').val());
$.ajax({
url: "#Url.Action("GetSelectedQuestion", "ConductSurveyController")",
data: { prefix: $('#DDlSurvey').val() },
type: "GET",
dataType: "json",
success: function (data) {
// loadData(data);
alert(data)
alert("Success");
},
error: function () {
alert("Failed! Please try again.");
}
});
//$('#YourLabelId').val('ReplaceWithThisValue');
}
</script>
Function I'm calling and I am getting dropdown value alert
Now, Function that I am calling is "GetSelectedQuestion" in controller "ConductSurveyController"
Method is like ,
[HttpPost]
public JsonResult GetSelectedQuestion(int prefix)
{
List<SelectList> Questions=new List<SelectList>();
// Here "MyDatabaseEntities " is dbContext, which is created at time of model creation.
SurveyAppEntities ObjectSur = new SurveyAppEntities();
// Questions = ObjectSur.Surveys.Where(a => a.ID.Equals(prefix)).toToList();
I don't think this method is calling as I am getting error
"Failed! Please try again"
From my script.
Hopes for your suggestions
Thanks
var e = from q in ObjectSur.Questions
join b in ObjectSur.SurveyQuestions on q.ID equals b.QuestionID where b.SurveyID.Equals(prefix)
select q ;
return new JsonResult { Data = e, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
I think you are using controller name straight forward. your ajax code be something like this.
var PostData= { prefix: $('#DDlSurvey').val() }
var ajaxOptions = {
type: "GET",
url: '#Url.Action("GetSelectedQuestion", "ConductSurvey")',//Actionname, ControllerName
data: PostData,
dataType: "json",
success: function (result) {
console.log(result);
},
error: function (result) {
}
};
$.ajax(ajaxOptions);
Your method in your controller is decorated with HttpPost, while in your ajax you have specified the type of your request is get . You can either change your method to get like this:
[HttpGet]
public JsonResult GetSelectedQuestion(int prefix)
{
}
Or change your request type to post in your Ajax call:
$.ajax({
url: "#Url.Action("GetSelectedQuestion", "ConductSurveyController")",
data: { prefix: $('#DDlSurvey').val() },
type: "Post",
Also the Controller is redundant in ConductSurveyController, you need to remove it and simply call it as ConductSurvey:
url: '#Url.Action("GetSelectedQuestion", "ConductSurvey")',
Java Script:-
function themechange(themeValue) {
$('#themeId').attr('href', '/zcv/resources/css' + '/' + 'theme-' + themeValue.toLowerCase() + '.css');
$.ajax({
url: '#Url.Action("ChangeTheme", "Login")',
type: 'GET',
dataType: 'json',
cache: false,
data: { 'themeValue': themeValue },
success: function (data) {
alert(data);
},
error: function () {
alert('Error occured');
}
});
}
In LoginContoller.cs:-
[HttpGet]
public JsonResult ChangeTheme(string themeValue)
{
System.Diagnostics.Debug.WriteLine("======ChangeTheme======");
Session["theme"] = themeValue;
String x= "========";
return Json(x, JsonRequestBehavior.AllowGet);
}
All the suggestion which replied so far are not working. Please give a executable project codes links for ASP.NET MVC Application which applies simple ajax with json for just calling a controller method.
You forget to assign the themeValue which get from HTML page by $('#themeId') also there is a problem you use GET instead of POST.
Try this
function themechange(themeValue) {
var themeValue = $('#themeId').attr('href', '/zcv/resources/css' + '/' + 'theme-' + themeValue.toLowerCase() + '.css');
$.ajax({
url: '#Url.Action("ChangeTheme", "Login")',
type: 'POST',
dataType: 'json',
cache: false,
data: { 'themeValue': themeValue },
success: function (data) {
alert(data);
},
error: function () {
alert('Error occured');
}
});
}
[HttpPost]
public JsonResult ChangeTheme(string themeValue)
{
System.Diagnostics.Debug.WriteLine("======ChangeTheme======");
Session["theme"] = themeValue;
String x= "========";
return Json(x, JsonRequestBehavior.AllowGet);
}
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
I faced a problem with IE and FF; my application is working with Google Chrome.
I am binding a model to a view in ASP.NET MVC
I have a table row inside a form(and some other controls). I replace the table row's content on a button click with ajax call. After ajax call, if I submit form as shown below, I can not get formcollection inputs from controller method. There is no problem when I submit form before ajax call.
The js code to update table row's content:
function reloadCriteriaTable(unitID, criteriaCode, icerikRowSpan, icerikOnay) {
$.ajax({
type: "GET",
url: 'ApproveParts/ReloadCriteria',
data: { contentID: $('[name="contentID"]').val(), unitID: unitID, criteriaCode: criteriaCode, selectedValue: $("#validator_" + criteriaCode).val(), icerikRowSpan: icerikRowSpan, icerikOnay: icerikOnay },
cache: false,
type: "POST",
success: function (data, textStatus, XMLHttpRequest) {
$('#tr_' + criteriaCode).replaceWith(data);
$('#continueBtn').on('click', function () {
$('#form_3').submit();
return false;
});
},
error: function (xhr, status, error) {
alert(xhr + ' ' + status + " : " + error);
}
});
}
Onclick function:
$(document).on("click", ".btnSubmitCriteria", function () {
$('#form_3').submit();
return false;
});
Controller method:
[HttpPost]
public ActionResult CourseCriteriaApprovment(FormCollection collection)
{
}
To begin with why you have mentioned both type "GET" and "POST" in your ajax call. Use "POST" only.
Try this
$.ajax({
type: 'POST',
url: '/ApproveParts/ReloadCriteria',
dataType: 'json',
contentType: 'application/json',
data : return JSON.stringify({
contentID: $('[name="contentID"]').val(),
unitID: unitID,
criteriaCode: criteriaCode,
selectedValue: $("#validator_" + criteriaCode).val(),
icerikRowSpan: icerikRowSpan,
icerikOnay: icerikOnay
});
});
In your controller action accept a class instead of FormCollection. Where the class has all properties defined same as the ones you are sending in your ajax call.
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.