jquery webmethod call returns whole page html - c#

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

Related

Chaining Controller Actions and/or promises in 1 button click

I currently have my project working about 75% of the time, I create report/reports add them to a zip, unzip them to a certain location. When I run this in debug mode it works correctly. When i run it normally sometimes the ajax will run out of order and it will try to unzip the file before its zipped (nothing is there). I have been doing trial and error with this trying many different methods to get this to work.
I tried multiple ways to do this: with the success: of ajax. I tried a .done promise after ajax. I tried a bool : if statement I tried many different conditions. It seems to finally be working in the correct order when i first open the project and select the records and the button click. Only 1 time it will do it successful.
When I try to select new records and run it a 2nd time the unzip folder isnt always created Or if it'll be created but will be empty (No reports unzipped to it).
Here is what I currently have which sometime works. Once I have this going good then I have to create the last step which will be to create an email and attach the document.
if (isValid) {
$.ajax({
type: "GET",
url: "/Service/ExportFiles/",
contentType: "application/json; charset=utf-8",
traditional: true,
data: { "quoteIDs" : arrSelectedChks },
success: function () {
window.location = '/Service/DownloadAsZip/';
// DownloadAsZip?mimeType=' + data;
},
error: function (request, status, error) {
alert("Error Generating Files");
//+ request.responseText);
}
}).done(function () {
$.ajax({
type: "POST",
url: "/Service/UnZipDownload",
data: {},
contentType: "application/json; charset=utf-8",
success: function (response) {
//alert("success in unzip");
CallEmail();
}
})
});
Here is another way i been doing this.
if (isValid) { /* At least 1 record is selected */
var phaseOne = $.ajax({
type: "GET",
async: false,
url: "/Service/ExportFiles/",
contentType: "application/json; charset=utf-8",
traditional: true,
data: { "quoteIDs": arrSelectedChks },
success: function (response) {
window.location = '/Service/DownloadAsZip';
successful = true
},
complete: function () {
if (successful)
isZipped = true;
}
});
}
$.when(phaseOne).always(function () {
if (isZipped) { /* Files are Zipped to start this phase */
$.ajax({
type: "POST",
async: false,
url: "/Service/UnZipDocument",
data: {},
contentType: "application/json; charset=utf-8",
traditional: true,
});
}
})
P.S. I have both Controller Actions UnZipDownload and UnZipDocument (both similar) if needing to see the action i will post.
You have to call your the second function only if the first is successful
if (isValid) {
$.ajax({
type: "GET",
url: "/Service/ExportFiles/",
contentType: "application/json; charset=utf-8",
traditional: true,
data: { "quoteIDs" : arrSelectedChks }
}).done(function(){
window.location = '/Service/DownloadAsZip/';
// DownloadAsZip?mimeType=' + data;
$.ajax({
type: "POST",
url: "/Service/UnZipDownload",
data: {},
contentType: "application/json; charset=utf-8"
}).done(function(){
//alert("success in unzip");
CallEmail();
});
}).fail(function(){
alert("Error Generating Files");
//+ request.responseText);
});
So I have tried SO MANY DIFFERENT results to try to get this to work with the click of 1 button. BUT the only way I have found out a way to get this to work is to have 1 button to do the report creating and zipping of the files. Then to have a second button (mines currently in a modal) and on this button click I am unzipping the file and creating the email. I have not been able to do everything all in 1 call. When I try my unzip functions is being called before my zip function I have tried many different ways to try to not have this happen [success, .done(), deferred objects, javascript promises]
$('#btnGetChkEmail').on('click', function() {
var arrChkBoxes = [];
var arrSelectedChks = [];
var myJSON = {};
var phaseOne, phaseTwo;
var isValid = false;
var bool = false;
var isZipped = false;
//var unZipped = false;
var successful = false;
// Turn all selected checkbox T/F values into QuoteIDs
$("input:checked").each(function (index, value) {
arrChkBoxes.push($(value).val());
});
// Push all Selected QIDs on NEW ARRAY
$.each(arrChkBoxes, function (key, value) {
if (IsPositiveInteger(value)) {
arrSelectedChks.push(value);
}
});
if (arrSelectedChks.length === 0) { // Create Modal (Error ~ None ~ Selected)
isValid = false;
alert("No Records Selected");
} else {
isValid = true;
}
/* EDITION LIKE GETCHKS */
if (isValid) {
$.ajax({
type: "GET",
url: "/Service/ExportFiles/",
contentType: "application/json; charset=utf-8",
traditional: true,
data: { "quoteIDs": arrSelectedChks },
success: function (response) {
window.location = '/Service/DownloadAsZip';
},
error: function (request, status, error) {
alert("Error Generating Reports");
}
}).done(function (data) {
/* Only way to do this 100% at the moment is to bring up a Button in a Modal */
var zipModal = $("#zipModEmail");
var modalHead = "<h3 class='modal-title'>Generate Email Messages</h3>";
var modalBody = "<span class='glyphicon glyphicon-ok-sign' style='font-size:5em; color:green;'></span>" +
"<p><b>Attach PDF's to email Confirmation</b></p>" +
"<p>Click 'OK' to Confirm</p>";
//var modalFoot = "";
zipModal.find(".modal-header").html(modalHead);
zipModal.find(".modal-header").addClass("alert-success");
zipModal.find(".modal-body").html(modalBody);
zipModal.modal("show");
});
}
$("#btnUnNemail").click(function (e) {
var myJSON = {};
var bool = false;
var ajaxCall = $.ajax({
type: "POST",
url: "/Service/UnZipDocument",
data: {},
contentType: "application/json; charset=utf-8",
success: function (response) {
debugger;
if (response.Status == "Unzipped") {
myJSON = { "Status": "Unzipped", "FilePath": response.FilePath, "FileName": response.FileName, "FileNames": response.FileNames };
bool = true;
}
$("#zipModEmail").modal("hide");
}
});
// Try switching to 'POST'
$.when(ajaxCall).then(function () {
if (bool) {
//debugger;
$.ajax({
type: "GET",
url: '#Url.Action("CreateEmailReport", "Service")',
contentType: "application/json; charset=utf-8;",
data: { "folderData": myJSON },
traditional: true,
})
}
});
});

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.

Calling handler from jQuery doesn't work

I need to call a handler (ashx) file from jQuery to fetch some data at runtime.
My jQuery function looks like:
var pID = 3;
var tID = 6;
$("#Button1").click(function() {
var urlToHandler = "Controller/TestHandler.ashx";
$.ajax({
type: "POST",
url: urlToHandler,
data: "{'pID':'" + pID + "', 'tID':'" + tID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
}
});
});
My handler code:
<%# WebHandler Language="C#" Class="TestHandler" %>
using System;
using System.Web;
public class TestHandler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
String pID = context.Request.Params["pID"];
String tID = context.Request.Params["tID"];
context.Response.ContentType = "text/plain";
context.Response.Write(pID + " " + tID);
}
public bool IsReusable
{
get {
return false;
}
}
}
The problem is the code execution doesn't reach to the handler code.
I can call other web forms (aspx) files from the same jQuery function from the same directory, where the handler file is residing. So it isn't any path issue.
I am new to this handler file concept. I googled a lot but couldn't find anything wrong in my code.
It worked after changing the way I was passing the json data (as suggested by #DRAKO) and removing the contentType from the ajax post back call. Also corrected the path.
$("#Button1").click(function() {
var urlToHandler = "TestHandler.ashx";
$.ajax({
type: "POST",
url: urlToHandler,
data: { pID: pID, tID: tID },
dataType: "json",
success: function(msg) {
//do something with the msg here...
}
});
});
I think the way you are passing the json data to the handler is incorrect.
Also make sure the path to the handler is correct and write a line to the console in the handler to check if it is getting called. Try this code out
$("#Button1").click(function(){
$.ajax({
type: "POST",
url: "/Controller/TestHandler.ashx",
data: {pID:pID, tID:tID},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
},
error: function(){
alert("Error");
}
});
});

C# webservice calls using jQuery 1.7.1 /eval/seq/

So here's the problem. I have three pages that make web service calls. The first time I land on the page and make the call it works fine, however if I switch to the second page it tries to make a web service call to the wrong service. Here's some info:
pages:
Page1.aspx - has Page1.js
Page2.aspx - has Page2.js
js files:
Page1.js
var filterCriteria = "";
function GetList() {
$.ajax({
type: "POST",
url: "/webServices/Page1.asmx/Page1List",
contentType: "application/json; charset=utf-8",
data: "{'letter':'" + filterCriteria + "'}",
dataType: "json",
success: function (result) {
DisplayList(result.d);
}
});
}
function GetSearchResults() {
$.ajax({
type: "POST",
url: "/webServices/Page1.asmx/Page1FilteredList",
contentType: "application/json; charset=utf-8",
data: "{'searchCriteria':'" + $("#Search").val() + "'}",
dataType: "json",
success: function (result) {
DisplayList(result.d);
}
});
}
function DisplayList(object) {
var html = '';
for (var i = 0; i < object.length; i++) {
//format results and append
}
if (object.length == 0) {
html += "<li class=\"filteredList\" style=\"padding: 10px;\">No Results Found</li>";
}
$("#Page1List").html(html);
}
Page2.js
var filterCriteria = "";
function GetList() {
$.ajax({
type: "POST",
url: "/webServices/Page2.asmx/Page2List",
contentType: "application/json; charset=utf-8",
data: "{'letter':'" + filterCriteria + "'}",
dataType: "json",
success: function (result) {
DisplayList(result.d);
}
});
}
function GetSearchResults() {
$.ajax({
type: "POST",
url: "/webServices/Page2.asmx/Page2FilteredList",
contentType: "application/json; charset=utf-8",
data: "{'searchCriteria':'" + $("#Search").val() + "'}",
dataType: "json",
success: function (result) {
DisplayList(result.d);
}
});
}
function DisplayList(object) {
var html = '';
for (var i = 0; i < object.length; i++) {
//format results and append
}
if (object.length == 0) {
html += "<li class=\"filteredList\" style=\"padding: 10px;\">No Results Found</li>";
}
$("#Page2List").html(html);
}
So both have the same calls and the same information and the only real difference is that the results are different and they make a web service call to different web services that get different data.
Now each time that I switch between I get a new js file which is
jQuery-1.7.1.min.js/eval/seq/1
jQuery-1.7.1.min.js/eval/seq/2
jQuery-1.7.1.min.js/eval/seq/3
jQuery-1.7.1.min.js/eval/seq/4
depending on how many times I switch back an forth. Is there any way to stop the eval or is there something in my code that is causing the jQuery to store evals of the code I am using and what can I do to resolve it?
So the problem was that I was loading page transitions from jquery mobile. What was happening was that jquery mobile appends new page data to the DOM instead of forcing a page load. This was causing both javascript files to be loaded simultaneously meaning that which ever js file was loaded last was the primary and because both js files were calling functions with the same name it would load them multiple times.
Resolution
remove the $.mobile.load() event and force the click event to append the pathname to the url
$("#GoPage1").on("click", function () { window.location = "/dir/Page1.aspx"; });
$("#GoPage2").on("click", function () { window.location = "/dir/Page2.aspx"; });

Is it possible to return a list<string> from a webmethod and pass the return value to bind a html select using jquery?

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
},
});

Categories

Resources