call a static method in User Control from js or ajax - asp.net

I am trying to call a static method in User Control from js or ajax.
It is possible to do this if the code method lies directly in WebForm but it is not possible to do it if we put the code method in UserControl and then put this UserControl in a WebForm.
Code Behind:
[WebMethod]
[ScriptMethod(ResponseFormat= ResponseFormat.Json)]
public static string GetNameFromCodeBehind (string name)
{
return "Hello from Code-Behind, " + name ;
}
AJAX Code:
$.ajax({
type: "POST",
url: "MyUserControl.ascx/GetNameFromCodeBehind",
data: JSON.stringify({ name: "Anton" }),
contentType: "application/json; charset=utf-8",
dataType: "json",
processdata: true,
success: function (data) {
alert(data.d);
},
error: function (e) {
alert(e.statusText)
}
});
Ajax Error:
Not Found

If GetNameFromCodeBehind is inside MyUserControl.ascx, then it will be able to find a URL. Moreover, you have written the name of static method as callFromCodeBehind. So, you need to write the URL sccordingly

Related

Call code-behind function from java script in c#

Is it even possible? To call a code-behind c# function from java script in a visual web part?
It is a complex function so converting all codes to client side is not an option.
I want the logic that is there in this function to happen without a page refresh.
Thanks.
We can call a method in codebehind from the JQuery AJAX call and depending upon the status whether it is error or success the corresponding method will be executed.
function MyMethod() {
$.ajax({
type: "POST",
url: "CodeBehind.aspx/ClearData",
contentType: "application/json;charset=utf-8",
data: '',
dataType: "json",
success: function (data, textStatus) {
closePopUpwindow1();
},
error: function (data, textStatus) {
closePopUpwindow2();
}
});}
[WebMethod]
public static void ClearData(){
Page.SetGridSessionData(gridID, null);
}
If the server side method is successfully executed then closePopUpwindow1 method is executed else closePopUpwindow2 method will be executed.
You can use j Query ajax to call server side method and get the response to be used in java script.
This article has simple and good example to show what you need to do.
public partial class _Default : Page
{
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
Java script
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}

how to use jQuery ajax with asp.net user controls?

I want to use ajax with asp.net user control,
$.ajax({
type: "POST",
url: "*TCSection.ascx/InsertTCSection",
data: "{id:'" + id + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var URL = msg.d;
alert(URL);
});
.cs code
[WebMethod]
public static string InsertTCSection(string id)
{
string result = "deneme";
return result;
}
You cannot call a method kept inside a usercontrol through jquery.
because .ascx controls don't represent real url.
They are meant to be embedded in some ASP.NET page, hence they don't exist at runtime.
what you might do is, to create a separate service and place your method there.
like webservices.
see this, this and many others
i am using generic Handler to solve this problem.
Try:
$.ajax({
type: "POST",
url: "*TCSection.ascx/InsertTCSection",
data: JSON2.stringify({ id: id}, //Your 2nd id is passing value but i dont know where its come from
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var URL = msg.d;
alert(URL);
}
)};
and in cs:
[WebMethod]
public static string InsertTCSection(string id)
{
string result="deneme";
return result;
}
I think you might be missing this attribute
[System.Web.Script.Services.ScriptService]
Before you service class as
[System.Web.Script.Services.ScriptService]
public class TCSection: System.Web.Services.WebService
{
[WebMethod]
public static string InsertTCSection(string id)
{
}
}
Or there may be one other reason that path of the webservice is not right.

converting object variable to json string for asp.net page method

This is probably a very simple task to perform but I'm taking the risk to ask anyway.
I have an object variable that looks like this:
var MyObj = {"Param1": "Default",
"Param2": "test",
"Param3": 3 };
I'm using ASP.net and I'm looking to pass this object to a page method via jquery.
So far, I have this javascript code:
function LoadObject () {
var TheObject = MyObj.toString();
$.ajax({
type: "POST",
url: "../Pages/TestPage.aspx/GetCount",
data: TheObject,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFn,
error: errorFn
});
};
I have a page method set up in the .cs file and I put a breakpoint in it but it never gets there; nothing happens.
Please let me know what changes I need to make to get this to work.
Thanks.
You need to serialize TheObject into a JSON string, and ensure that the GetCount method accepts an object with the same signature as TheObject.
I use the jQuery.JSON library to do this so that my syntax becomes:
data: "{ methodParameterName: " + $.toJSON(TheObject) + " }"
I use this library, but you can acheive the same thing with any other library in a similar manner
The first thing that you need to know is that you need to match your method name with your url
for example if your method on your code behind is named "calculate", your url must be something like this "../Pages/TestPage.aspx/calculate"
other thing that you need to keep in mind is the parameters of your method, the names and the types of your parameters must match in you ajax call and your method (code behind)
if the sign of your method is something like this
[WebMethod]
public void Calculate(string data){
// your code here
}
Your ajax call must be like this:
function LoadObject () {
var objetoJson = {
data: JSON.stringify(MyObj)
};
$.ajax({
type: "POST",
url: "../Pages/TestPage.aspx/Calculate",
data: objetoJson ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFn,
error: errorFn
});
};
This section is so important:
var objetoJson = {
data: JSON.stringify(MyObj)
};
the name "data" is the name of your parameter in your method (code behind) and "JSON.stringify" is a helper functions already defined on your browser to convert and object to string
Hope this helps
Take a look at this thread: JSON stringify missing from jQuery 1.4.1?
Abstract: jQuery doesn't have a native method to do it. But there are many plugins out there.
EDIT
Sample C# code receiving your JSON object:
[WebMethod]
public static int GetCount(GetCountParams p)
{
// ... Do something with p.Param1, p.Param2, etc.
return 0;
}
public class GetCountParams
{
public string Param1 { get; set; }
public string Param2 { get; set; }
public string Param3 { get; set; }
}
EDIT 2
Sample jQuery AJAX call using that object as parameter:
$.ajax({
type: "POST",
url: "../Pages/TestPage.aspx/GetCount",
data: "{ p: '" JSON.stringify(MyObj) + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json"
});

jQuery + ASP.NET 4.0 ajax page method not working

I have used whole lots of options resolving this, but it is not working.
My breakpoint is not hit in the Web Method. Also, the success function is being called, however, entire page content is returned not the string "hello".
My page does not at all use asp.net ajax scriptmanager. It uses plain jQuery only. I am using ASP.NET 4.0.
In brief, my page method is defined as:
[WebMethod]
public static string Populate()
{
return "hello";
}
The ajax call is:
$.ajax({
url:'WebForm3.aspx/Populate',
data:{},
dataType:"json",
type:"GET",
success: function(msg) {
alert("success");
},
error: function(msg, text) {
alert(text);
}
});
Page methods only work when POSTed to, like this:
$.ajax({
url:'WebForm3.aspx/Populate',
data: '{}',
dataType:"json",
type:"POST",
contentType: 'application/json; charset=utf-8',
success: function(msg) {
alert("success"); },
error: function(msg, text) {
alert(text);
}
});
Don't forget to quote the data argument: data: '{}'.

using jQuery AJAX with asp.net webservices always goes to error: instead of success:

Issue
I have an aspx page with jQuery code to send an ajax request over to an asmx web service file (on the same website). The response that comes back is not consistent, however, it consistently fires the "error" jQuery callback as opposed to the "success" call back. The status code inconsistently varies between 200, 12030, and 12031. The responseText of the message to the callback inconsistently varies between [blank] and the actual XML that the json webservice returns. I debugged the code, and the webservice does actually execute without any exceptions.
ASPX Code
//Code omitted for brevity
<script type="text/javascript">
jQuery(document).ready(function()
{
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "CallDequeue.asmx/Dequeue",
data: "{}",
dataType: "json",
success: function(Msg)
{
alert('success:' + Msg.responseText);
},
error: function(Msg)
{
alert('failed:' + Msg.status + ':' + Msg.responseText);
}
});
});
</script>
//Code ommitted for brevity
Web Service Code
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class CallDequeue : System.Web.Services.WebService
{
[WebMethod]
public string Dequeue()
{
return "{\"d\":{\"FirstName\":\"Keivan\"}}";
}
}
When you mark the service as a ScriptService, it automatically handles the JSON serialization. You shouldn't manually serialize the response.
If you want the return to come back as "FirstName", then you can use a DTO class to control the syntax. Just returning a string, it would come back as {'d':'Keivan'} instead of {'d':{'FirstName':'Keivan'}}.
[ScriptService]
public class CallDequeue : System.Web.Services.WebService
{
public class PersonDTO
{
public string FirstName;
}
[WebMethod]
public PersonDTO Dequeue()
{
var p = new PersonDTO();
p.FirstName = "Keivan";
return p;
}
}
A few changes to the calling syntax:
jQuery(document).ready(function() {
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "CallDequeue.asmx/Dequeue",
data: "{}",
dataType: "json",
success: function(Msg) {
// Unless you're using 2.0, the data comes back wrapped
// in a .d object.
//
// This would just be Msg.d if you return a string instead
// of the DTO.
alert('success:' + Msg.d.FirstName);
},
error: function(Msg) {
alert('failed:' + Msg.status + ':' + Msg.responseText);
}
});
});
You can read more about ASP.NET AJAX's .d wrapper here, if you're interested.
Update:
Using ASP.NET 2.0, you need to install the ASP.NET AJAX Extensions v1.0. Additionally, make sure your web.config is configured for ASP.NET AJAX (most specifically the HttpHandlers section).
This question will most likely help you.
Otherwise, I converted this web service to a page method and it worked immediately. Do you have that option?
CS:
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string Dequeue()
{
return "{\"d\":{\"FirstName\":\"Keivan\"}}";
}
}
ASPX:
<script type="text/javascript">
jQuery(document).ready(function()
{
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "test.aspx/Dequeue",
data: "{}",
dataType: "json",
success: function(Msg)
{
alert('success:' + Msg.responseText);
},
error: function(Msg)
{
alert('failed:' + Msg.status + ':' + Msg.responseText);
}
});
});
Check this and other Encosia articles out for more information.
you say it's json, but it returns xml. i see a slight disconnect there.
Such a simple answer. My web.config wasn't ajax enabled so all calls (regardless of my webservice being a scriptservice) were returning XML instead of pure json.
Try marking up your web method with [ScriptMethod]
As in:
[WebMethod]
[ScriptMethod]
My thanks to all the responders here.
Be sure to add these attributes in front of the methods to be used
[WebMethod]
[ScriptMethod]
Not sure when the ScriptMethod is needed ?
Curiously, he did NOT have the [Script Service] and the [WebMethod] in his download code.
Anyway, the aJax 500 12030 12031 errors are gone after the above changes.

Resources