Data not received in C# method, which is sent through $.ajax() - c#

I am sending a complex string (which is a combination of the style attribute, ID and label text) from the script using $.ajax() . I went through a couple of questions on similar problems. But maybe I am not able to understand where am I getting it wrong.
This is the script I am using :
$(".btnSaveStyle").click(function (e) {
var comp1Style = "";
var comp2Style = "";
$(".box").children(".comp1").each(function () {
var style = $(this).attr('style');
var title = $(this).text();
var componentClass = $(this).attr('class');
comp1Style = comp1Style + style + "#" + componentClass + "#" + title + "$";
});
alert(comp1Style); //I get the style here
$.ajax({
type: "POST",
async: true,
url: 'AjaxRecieveStyle.aspx/GetStyle',
data: comp1Style
});
And in the C# I am accessing it in the following way :
[WebMethod]
protected void GetStyle(string style)
{
var recievedStyle = style;
Customer customer = (Customer)Session["existing_user"];
if (customer != null)
{
EventComponent eventComponent = new EventComponent();
string txtComp1 = recievedStyle;
string[] separateComponents = txtComp1.Split('$');
string[] individualComponent = new string[5];
foreach (string position in separateComponents)
{
individualComponent = position.Split('#');
if (individualComponent[0].Equals(""))
{
//do nothing
}
else
{
eventComponent.EventID = 1;
eventComponent.Image = "";
eventComponent.Style = individualComponent[0].ToString();
eventComponent.ComponentType = individualComponent[1].ToString();
eventComponent.Title = individualComponent[2].ToString();
int id = new EventComponentLogic().Insert(eventComponent);
}
}
}
}
Now :
1) : Should I use a JSON object to pass the data ?
OR
2) : Please show me what am i doing wrong in here ?

1) Yes it's better to send data using JSON - I mean, it'd be much easier to understand what's happening when anyone will look at that code in a year from now. And it's also much easier to extend the protocol based on JSON.
2) I suggest you to add logging at the very beginning of the GetStyle(string style) method. Then please try to get to it by explicitly typing the URL in your browser (or better using PostMan - see below for a link, PostMan will help you with testing POST requests as I see you have a POST request there) and ensure that the web-server code works.
And only if it works then please try your front-end AJAX request.
I suppose that you don't handle POST request correctly in your WebAPI. It will only handle GET requests. Please look at this SO question for details: Simple post to Web Api
3) Link to PostMan: https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?hl=en

Did some digging and came up with this link: http://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx
The source code from the website shows that you may be missing some key features in your ajax call:
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "Default.aspx/GetCurrentTime",
data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response.d);
}
});
}
While this is (obviously) intended for their example you see that they set the following attributes that you do not
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response.d);
}
While the success and failure attributes are definitely optional I believe that setting your content type and datatype would really help you out here.

I changed my script to the following :
$.ajax({
type: "POST",
async: true,
url: 'AjaxRecieveStyle.aspx',
data: { style: comp1Style } //as I want to pass the parameter 'style' which is internally a JSON array.
});
I fetched the variable style in my C# in the following way (without using [WebServices]) :
I wrote a method GetStyle(string style) to get the data being sent from the ajax call.
Note: I did not call AjaxRecieveStyle/GetStyle from my script as the method is not accessible in my C# method . The data is actually received from the Page_Load method.
I access the variable sent from the script using Request.Params["style"].
My C# method is :
protected void Page_Load(object sender, EventArgs e)
{
GetStyle(Request.Params["style"]);
}
protected void GetStyle(string style)
{
var recievedStyle = style;
//do something on the recieved data!
}
This wil be an alternative to anyone who don't want to send JSON data actually !But sending data using JSON format will increase the readability of the code..

Related

Ajax call always returning error

I'm having trouble with calling a WebMethod with Jquery.
function runQuery(e) {
var search = $(e).val();
var csKind;
if ($('#rbLP').is(':checked'))
csKind = 1;
else
csKind = 0;
var params = {
url: 'addEditProduct.ascx/AutoComplete_Press',
method: 'post',
contentType: 'application/json',
data: JSON.stringify(search),
dataType: 'json',
success: function(data) {
alert(1);
},
error: function(data) {
alert(2);
}
};
$.ajax(params);
}
[WebMethod]
public static void AutoComplete_Press(string searchClause, int csKind)
{
int searchType = 0; //ЕГН
Regex regex = new Regex("^[0-9]+$");
if (!regex.IsMatch(searchClause))
searchType = 1;
string clients = laboratory.getClients2(searchType, searchClause, csKind);
}
How can I diagnose the problem, I've never used ajax before and I'm at a loss.
The problem I can see here is your passing arguments:
data: JSON.stringify(search),
you are missing csKind, maybe change this line to
data: "{searchClause: '" + search + "',csKind: '" + csKind + "'}",
And change your method to :
public static void AutoComplete_Press(string searchClause, string csKind)
The url seems to be wrong if you ask me. Open up your console in the browser and see what it says, it will be throwing cant connect/connection refused error. Also open network in the browser and you can check what http response you are getting. This will help u start up diagnosing the problem.

How to obtain checked checkbox values on the serverside in c# from an ajax Http POST using web forms (not MVC)?

Here's my ajax call:
$(function () {
$("#chkFilter").on("click", "input", function (e)
{
var filterCheckboxes = new Array();
$("#chkFilter").find("input:checked").each(function () {
//console.log($(this).val()); //works fine
filterCheckboxes.push($(this).prop("name") + "=" + $(this).val());
console.log($(this).prop("name") + "=" + $(this).val());
//var filterCheckboxes = new Array();
//for (var i = 0; i < e.length; i++) {
// if (e[i].checked)
// filterCheckboxes.push(e[i].value);
//}
});
console.log("calling ajax");
$.ajax({
url: "/tools/oppy/Default",
type: "POST",
dataType: "json",
data: { filterValues: filterCheckboxes }, // using the parameter name
success: function (result) {
if (result.success) {
}
else {
}
}
});
});
});
And my server side code:
public partial class tools_oppy_Default : System.Web.UI.Page
{
...
protected void Page_Load(object sender, EventArgs e)
{
if (Request.HttpMethod == "POST")
{
string checkedBoxes = Request["filterValues"];
testLabel.Text = checkedBoxes;
}
I'm just trying to obtain the post URL with the appropriate checked values so I can parse it on the server. However, I'm having trouble obtaining the URL. The string checkedBoxes is supposed to hold a query string like name=value&name=value&name.... but when I test it, the testLabel doesn't show anything. I'm using web forms app, not MVC. Also, I'm new to ajax and their behavior. Thanks.
First, I assume that the url in you JQuery call is valid as there is not aspx extension their.
Second, It looks like what you need to do is create a web method and call it from JQuery for example the following is a web method that accept string
[WebMethod]
public static string GetData(String input)
{
return DateTime.Now.ToString();
}
and you can call it using the same way with your current code just update the url parameter to include the method name
url: "PageName.aspx/MethodName",
for more details about web methods and their union with JQuery please check this article
Edited The following is complete sample
The web method should look like the following one
[WebMethod]
public static string GetData(string filterValues)
{
return filterValues; //This should be updated to return whatever value you need
}
The client side part of calling the web method should look like the following
$.ajax({
url: "/Default/GetData",
type: "POST",
contentType: "application/json; charset=utf-8", //I have added this as "contentType" parameter represents the type of data inside the request meanwhile the "data" parameter describes the data inside the response
data: "{ filterValues:\"" + filterCheckboxes + "\"}", //Note that I have updated the string here also set the name of the parameter similar to the input of the webmethod
dataType: "json",
success: function (result) {
alert(result.d);//You should access the data using the ".d"
}
});
One last thing, If you are using asp.net permanent routing the above code will not work and you should disable it by updating the file "App_Code/RouteConfig.cs" From
settings.AutoRedirectMode = RedirectMode.Permanent;
To
settings.AutoRedirectMode = RedirectMode.Off;
And remember to clear browser cache after the above update

Cannot pass large json string to another Page with asp.net c# and knockoutjs

I got a problem while working with knockoutJs and asp.net c#.
When I passed a json string from page to another popup page using jquery ajax and knockoutJs for printing.
The problem occur:
When the Json string is small. It works fine, the popup page shows string data in table.
However, when the json string is large. It doesn't work anymore. The error occurs with message:
"Uncaught Sys.ArgumentException: Sys.ArgumentException: Cannot deserialize. The data does not correspond to valid JSON.
Parameter name: data"
Here is my code:
$.ajax({
type: "POST",
url: 'InProgressBrief.aspx/PrintReport',
data: ko.toJSON({ reportData: ko.toJSON(InProgressBriefs.Briefs) }),
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
window.open("PrintInProgressBrief.aspx?month=" + InProgressBriefs.Month() + "&year=" + InProgressBriefs.Year(), "", "status=0,toolbar=0,width=1000,height=900");
}
})
Here is my webMethod
[WebMethod]
public static void PrintReport(string reportData)
{
PSCDialog.DataShare = reportData;
}
The popup page recieves the Json tring:
if (PSCDialog.DataShare != null)
return PSCDialog.DataShare as string;
In the popup page UI, I set the knockoutjs variable, my UI javascript code is something like follow:
var InProgressBriefs = {
Briefs: ""
;
$(function(){
InProgressBriefs.Briefs = Sys.Serialization.JavaScriptSerializer.deserialize('<%=ReportJSONData%>');
ko.applyBindings(InProgressBriefs, $('#mainDivPrint')[0]);
})
Would anyone please tell me what is the problem here? I will appreciate your help alot.
Thank you in advance.
One thing that's a little suspicious is the line
data: ko.toJSON({ reportData: ko.toJSON(InProgressBriefs.Briefs) }),
When that's deserialized, you wind up with reportData being a JSON-encoded string rather than a native object. I doubt that's what you want. More likely what you need is
data: ko.toJSON({ reportData: ko.toJS(InProgressBriefs.Briefs) }),
which serializes only once.

How to pass Stringified JSON to C# Method?

I've spent the last night trying to figure this out.
Basically in Google Maps, I am able to generate directions, or waypoints, between two points that the user chooses in client side Javascript.
I ideally want to be able to store these in my database ( Im using C#.NET and SQL Server DB ) by passing these to a server side C# method..
I've got to the point where I can put the directions I need into a string by using:
*var string = JSON.stringify(response);*
Now, here's where I'm stuck.
How do I pass this to a C# webforms method?
I've seen an MVC C# solution to my problem as:
var str = JSON.stringify(data)
var city = {};
city.Directions = str;
$.ajax({
type: 'POST',
url: 'usertrip.aspx/GetDirections',
data: str ,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (r) {
alert(r.d.Directions);;
}
});
But I've tested, and have concluded that this won't work for webforms. Does anyone know how I can alter this code so that I can pass the string to a Webforms method and not MVC?
Thanks!
You can definitely do this kind of thing with webforms. The important thing is that you need to set up a webservice that exposes methods that can be hit by the ajax call. This awesome article called Using jQuery to directly call ASP.NET AJAX page methods proved invaluable for me to figure out how to accomplish what you're trying to do.
For an example (from the article) doing something like this:
public partial class _Default : Page
{
[WebMethod]
public static string DoSomething(string myJsonData)
{
// deserialize your JSON
// do something cool with it
}
}
Would allow you to hit the webmethod with your AJAX call. I can assure you that I've done this in many different asp.net solutions what don't use MVC so with a little bit of tinkering you should be able to get the information you need to your code behind.
You would need to do something like :
var str = JSON.stringify(data)
var city = {};
city.Directions = str;
$.ajax({
type: 'POST',
url: 'usertrip.aspx/GetDirections',
data: { city: str },
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (r) {
alert(r.d.Directions);;
}
});
And in the Webforms code behind:
City city = new JavaScriptSerializer().Deserialize<City>(Request.Form["city"]);

asp.net pass sender to server with jquery

I want to call a C# function in my aspx.cs file with jQuery. The function looks like:
protected void Fill(object sender, EventArgs e) { ...do s.th. with sender... }
in the function im getting my control I want to work with by doing a cast on the sender. How to pass the sender to server with jquery?
Check this : Implementing Client Callbacks Programmatically Without Postbacks in ASP.NET Web Pages
OR
Hi you can check this article : http://pranayamr.blogspot.com/2012/01/calling-server-side-function-from.html which dicuss about calling server method with the jQuery function.
cs file i.e serverside code
[WebMethod]
public static string IsExists(string value)
{ return "True"; }
Client script
function IsExists(pagePath, dataString, textboxid, errorlableid) {
//alert(pagePath);
$.ajax({
type: "POST",
url: pagePath,
data: dataString,
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function(XMLHttpRequest, textStatus, errorThrown) {
$(errorlableid).show();
$(errorlableid).html("Error");
},
success:
function(result) {
var flg = true;
if (result != null) {
debugger;
flg = result.d;
if (flg == "True") {
$(errorlableid).show();
}
else {
$(errorlableid).hide();
}
}
}
});
}
function focuslost() {
var pagePath = window.location.pathname + "/IsExists";
var dataString = "{ 'value':'" + $("#<%= txtData.ClientID%>").val() + "' }";
var textboxid = "#<%= txtData.ClientID%>";
var errorlableid = "#<%= lblError.ClientID%>";
IsExists(pagePath, dataString, textboxid, errorlableid);
}
You can't call functions just like that with jQuery. jQuery is a client scripting technology based on javascript that runs on the client browser. It doesn't know what ASP.NET is. It even less knows what a server side, ASP.NET code behind method is.
This being said, you could send an AJAX request to a server side script which in your case could be either a generic handler (.ASHX) or an .ASPX page. In this second case you could use Page Methods.

Categories

Resources