How to pass Stringified JSON to C# Method? - c#

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"]);

Related

passing a parameter from jQuery ajax call to C# method in web forms

I'm tring to pass a value I pull from a data-attribute in my markup to a C# method using jQuery Ajax. In this example, the value for QuestionNumber results in a 1. EMHQQuestion is an enum with values 1 through 15. I expect my C# method DeleteCondition to receive that 1 but instead I get a 500 internal server error: "Invalid web service call, missing value for parameter: 'questionNumber'.
Any suggestions?
function DeleteConditions() {
var QuestionNumber = $('.noRadioButton').data('questionnumber');
$.ajax({
url: "mhqpreinterview.aspx/deletecondition",
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
questionNumber: QuestionNumber
});
Dialog.dialog('close');
}
..
[WebMethod(EnableSession = true)]
public static void DeleteCondition(EMHQQuestion questionNumber)
{
//stuff
}
I struggled with this EXACT same thing when making AJAX reqs to web form methods.
For your c# method:
[System.Web.Services.WebMethod()]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string DeleteCondition(EMHQQuestion questionNumber)
{
// do enum stuff here
}
Please note that I have changed the method type from void to string. It is a good idea to send some identifiable information back to the client. Even if you do not have to send data back, it gives you a chance to customize success or helpful debugging information.
Here are the changes you have to make to your AJAX object:
var params = '{ questionNumber: ' + JSON.stringify(QuestionNumber) + '}';
var post = {
type: 'POST',
url: 'mhqpreinterview.aspx/deletecondition',
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json"
};
$.ajax(post);
What you should be taking away from the above javascript, is the use of JSON.stringify before you send to your method. You have to make sure QuestionNumber is parameterized correctly and already valid JSON for the web service method to receive.
If you find its still not working, check to see what value is being stored inside QuestionNumber before you are trying to send it.
The above code does work with me, any other troubles post a comment and I will do my best to help answer it.
Use data jquery ajax field:
data: JSON.stringify({QuestionNumber: QuestionNumber}),
dataType: "json",

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

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..

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.

Sending variable to a C# inside Javascript code

Javascript Code:
function jsfunction ()
{
var sayi = 9999;
alert('<%= cfunction("'+sayi+'")%>');
}
C# Code:
public string cfunction(string gelen)
{
return gelen;
}
Normally,There is should be 9999 value which is send to C# code from javascript code,but,this value returning as '+sayi+'.
Also,that's gives me alert 9999.What am I wrong?
By the time JavaScript runs, the C# code has already been executed. Learn you page life cycle.
If you want to call a serverside function to get data, you need to learn about Ajax.
C# (server-side) can generate markup for client side, client side can't call back up to server-side without some kind of Ajax type web request.
To do what you're looking for you can create a C# webmethod
[WebMethod()]
public static string cfunction(string gelen)
{
return gelen;
}
And consume the webmethod with a client-side jQuery.ajax() method (You'll need the jQuery library script if you don't have it already)
function jsfunction() {
var sayi = 9999;
$.ajax({
type: "POST",
url: "YOUR-ASPX-PAGE.aspx/cfunction",
data: "{gelen:'" + sayi + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d);
}
});
}
You can use scriptmethod attribute to invoke server side method from your javascript code. But you must understand the mechanism behind it so that u can debug and modify accordingly.
http://www.chadscharf.com/index.php/2009/11/creating-a-page-method-scriptmethod-within-an-ascx-user-control-using-ajax-json-base-classes-and-reflection/

Using PageMethods with jQuery

Simply put I want to call public static methods decorated with WebMethod attribute inside my code-behind C# file from jquery.ajax to get some json and other simple stuff (in different functions). But instead I'm getting whole page :'(
I'm not using asp.net AJAX though I'm developing for .NET 3.5 framework and using VS 2008. (There are some restrictions from client)
Please let me know if I can use page-methods with using asp.net ajax or If not what is other simple solution?
After much deliberations I found the problem. I was using jquery's editable plugin. This was source of the problem. When jeditable calls jquery's ajax it sets ajax options like this:
var ajaxoptions = {
type: 'POST',
data: submitdata,
url: settings.target,
success: function(result, status) {
if (ajaxoptions.dataType == 'html') {
$(self).html(result);
}
self.editing = false;
callback.apply(self, [result, settings]);
if (!$.trim($(self).html())) {
$(self).html(settings.placeholder);
}
},
error: function(xhr, status, error) {
onerror.apply(form, [settings, self, xhr]);
}
};
so it was sending the things as simple html and to use this with page methods we need to setup the things so that it sends as json. So we need to add something to the settings like this:
var ajaxoptions = {
type: 'POST',
data: submitdata,
url: settings.target,
dataType: 'json', //Data Type
contentType: 'application/json; charset=utf-8', //Content Type
//....other settings
};
So I put two new properties in settings dataType and contentType and changed above to this:
var ajaxoptions = {
type: 'POST',
data: submitdata,
url: settings.target,
dataType: settings.dataType,
contentType: settings.contentType,
//....other settings
};
Now another problem arised :( it was sending data (from submitdata property) as normal query-string which asp.net does not accept with json requests. So I had to use jquery's json plugin and change the way data is sent in ajax using following test on dataType:
if (settings.dataType == "json") {
if ($.toJSON) {
submitdata = $.toJSON(submitdata);
}
}
and it works like breeze!!!
Russ Cam posted this link in response to another question (so if this helps, go up vote his answer ;)):
Using jQuery to directly call ASP.NET AJAX Page Methods
Dave Ward has a series of posts that use jQuery directly with ASP.Net PageMethods, no MS Ajax UpdatePanel required. In particular this post will get you started.
I am not sure but i think WebMethods are accessible only through asp.net AJAX. I may be wrong though, because we dont use it that way at all. We do it in a slightly different way.
We have built a aspx page which accepts all our AJAX requests and passes them to the subsequent methods.
Server side code
If Not (Request("method") Is Nothing) Then
method = Request("method")
username = HttpContext.Current.User.Identity.Name.ToString
Select Case UCase(method)
Case "GETPROJECTS"
Response.ContentType = "text/json"
Response.Write(GetProjects(Request("cid"), Request("status")))
Exit Select
end select
end if
Client Side code [using jquery]
$.ajaxSetup({
error: function(xhr, msg) { alert(xhr, msg) },
type: "POST",
url: "Ajax.aspx",
beforeSend: function() { showLoader(el); },
data: { method: 'GetProjects', cid: "2", status:"open"},
success: function(msg) {
var data = JSON.parse(msg);
alert(data.Message);
},
complete: function() { hideLoader(el); }
});
Hope this helps.

Categories

Resources