How to Call Default.aspx.cs page method from Jquery Ajax? - asp.net

I have a registration form(Default.aspx) which initially show's only 2 field's and a button (Name, email) when user click's on button Jquery makes an Ajax call to Default.aspx.cs function which query db to check for the user, and if it return no then the form expands itself adding registration fields.
I am not able to make a call to Defualt.aspx.cs
my Default.aspx code is :
<script type="text/javascript">
$(document).ready(function() {
$('#btnDownload').click(function() {
//$('#secondary').toggle(1000)
$.ajax({
type: "POST",
url: "Default.aspx/PassData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
});
function AjaxSucceeded(result) {
alert(result.d);
}
function AjaxFailed(result) {
alert('Failed');
}
});
</script>
And Default.aspx.cs is (for test purpose) :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private static string PassData(string id)
{
return "Pass";
}
}
But every-time I run the code JS returns error :
Uncaught ReferenceError: com is not defined
POST http://localhost:2305/temp/Default.aspx/PassData 500 (Internal Server Error)
I check few posts but non of them had been answered/resolved.
Any kind of help would be highly appreciated.
Thanks in advance

You need to decorate the method with [WebMethod] attribute.
EDIT
You'll need to add a ScriptManager and use some ASP.NET ajax framework methods. I think what you want to do is impossible with the out-of-the-box functionality.
One option will be to create a HttpHandler that will handle those methods. If the request is a POST, you can find the page type from the url (there's a method in the framework but I can't remember which one, you'll need to investigate), create a new instance and check if the method has the WebMethod (or another attribute you like). If it does, you can call it using reflection and render the result.
EDIT
As #Antony Highsky pointed out, it's possible. I think the solution is to add the [WebMethod] attribute and make de method public (it's private in the example).

Use **[WebMethod]
[WebMethod]
private static string PassData(string id)
{
return "Pass";
}

Related

how to call a c# webmethod on mouseover of linkbutton in asp.net?

Is it possible to call a c# webmethod on mouseover on Linkbutton ? what i want is to call a webmethod in which i am binding a repeater control with datatable. How?
in aspx:
<asp:LinkButton Text='<%#Eval("SNA")%>' ID="lnkpro1" runat="server"
CssClass="linkbutton" servicemethod="GetRecords"
OnClick="btn_Click1" CommandArgument='<%# Eval("Sets") %>'></asp:LinkButton>
in aspx.cs:
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public void GetRecords(object sender, EventArgs e)
{
}
I am not getting the point that is how is it possible to call a webmethod on linkbutton mouseover. I have used a webmethod in textbox autocomplete extender but it has a propperty of calling a webmethod but is it so in this case also? Thank you.
Use ASP.NET AJAX Page Methods, like this:
[WebMethod]
public static List<Record> GetRecords()
{
// Go to database to get list of records
List<Record> listOfRecords = GetRecordsFromDatabase();
return listOfRecords;
}
I made up the Record class here. A list of something needs to be returned, so I made it up for the example's sake.
Note: ASP.NET AJAX Page Methods automatically JSON-encode their response, so there is no need for serialization in the page method if you are using JSON on the client-side.
Now you can call the ASP.NET AJAX Page Method, like this:
$(document).ready(function() {
$('.linkbutton').mouseover(function() {
$.ajax({
type: "POST",
url: "PageName.aspx/GetRecords",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
// Do something with records returned here
// Use result.d to get to JSON data
}
});
});
});
You can do that using jQuery Ajax method to call a WebMethod:
Refer this for an ultimate example for Calling an ASP.NET C# WebMethod

Why Can WebMethod Access Session State Without EnableSessionState?

I have a method on a page marked as a [WebMethod] that uses some session state as part of its operation. After I wrote this code, I suddenly had a flash of memory that you need to use EnableSessionState when you use session state in a [WebMethod] (e.g. see here: http://msdn.microsoft.com/en-us/library/byxd99hx.aspx). But it seems to be working fine. Why?
Sample code behind:
protected void Page_Load(object sender, EventArgs args) {
this.Session["variable"] = "hey there";
}
[System.Web.Services.WebMethod]
public static string GetSessionVariable() {
return (string)HttpContext.Current.Session["variable"];
}
Sample body html:
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function getSession() {
$.ajax({
type: 'POST',
url: 'Default.aspx/GetSessionVariable',
data: '{ }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
document.getElementById("showSessionVariable").innerHTML = msg.d;
}
});
return false;
}
</script>
<form id="form1" runat="server">
<div id="showSessionVariable"></div>
<button onclick='return getSession()'>Get Session Variable</button>
</form>
On http://msdn.microsoft.com/en-us/library/system.web.services.webmethodattribute.enablesession(v=vs.90).aspx, you will see that this applies to XML Web services (i.e., classes derived from System.Web.Services.WebService).
[WebMethod(EnableSession=true)]
Because your page presumably extends System.Web.UI.Page, it is not necessary to explicitly enable the session. On http://msdn.microsoft.com/en-us/library/system.web.configuration.pagessection.enablesessionstate.aspx, you can see that EnableSessionState is enabled by default for Pages (which you probably already know).
http://forums.asp.net/t/1630792.aspx/1
Answer of gsndotnet:
You are right but whatever you are saying is applicable to a method in context of WebServices. We also use same WebMethod attribute on the methods of a WebService (.asmx). So in context of Web Services when we want to allow the access to Session we have to add EnableSession = true. Whereas in context of PageMethods they already have access to Session as they are defined inside a class that inherits from Page class.
Your msdn link means that you use web service, i.e. class derived from System.Web.Services.WebService.
In your code you add your method directly on page, so it has access to session.

Create New Asmx Page in asp.net

I am creating an asmx web service.
In visual studio 2012 on the project name I right clicked and added an web service name UserDetails.asmx
Now I am trying to use the web service in the js file. like this
$.ajax({
type: "POST",
url: "UserDetails.asmx/HelloWorld",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert('success');
},
error: function () {
alert("Error");
}
});
Its showing error that POST http: //192.168.9.185/GPS/UserDetails.asmx/HelloWorld 500 (Internal Server Error)
Is there any fault in my code or I am missing something so that its showing error.
My Asmx Page
<%# WebService Language="C#" CodeBehind="~/App_Code/UserDetails.cs" Class="UserDetails" %>
My Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
/// <summary>
/// Summary description for UserDetails
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class UserDetails : System.Web.Services.WebService {
public UserDetails () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
}
Edit
Short Answer: just uncomment [System.Web.Script.Services.ScriptService]
Digging deep in the error message by using
error: function (xhr,status, error) {
alert("Error");
}
and inspecting xhr revealed that the actual error was something else (Only Web services with a [ScriptService] attribute on the class definition can be called from script).
I used [WebMethod] in my aspx code behind and whenever I received such message, I found out that there was an error in the data I am passing. So try adding data:"{}", in your $.ajax()
as described in this post
When making a read-only request, the empty data parameter is the key. For reasons unknown, jQuery does not properly set the specified content-type when there is no data included.

ajax request Mootools to asp.net webforms

I am trying to post a request to the server but it wont hit when I use the debugger?
server:
public partial class _Default : System.Web.UI.Page
{
public string HitThis()
{
return "braza";
}
}
<script type="text/javascript">
var myRequest = new Request({
method: 'post',
url: '/Default.aspx/HitThis',
onSuccess: function () {
alert('good');
},
onFailure: function () {
alert('nope');
}
});
myRequest.send();
</script>
If you want to be able to call your HitThis method, you need to make that method, static, decorate it with the Web Method attribute and enable Page Methods on your ScriptManager
Example:
<asp:ScriptManager ID="ScriptManager" runat="server"
EnablePageMethods="true" />
[WebMethod]
public static string HitThis()
{
return "Hello World";
}
You need to first understand how ASP.NET AJAX Script Services or PageMethod works! Page Methods has to be decorated with the WebMethod attribute and needs to be static.
[WebMethod]
public static string HitThis()
{
}
See this article that illustrates calling page method using jquery. You can adopt it with mootools. However, note that page methods needs content type to be JSON data and response will also be in JSON.
Perhaps you can write your own wiring logic in the ASP.NET page using Request.PathInfo if you want to use normal form posting. For example,
protected void Page_Load(object sender, EventArgs e)
{
if (this.Request.PathInfo == "HitThis")
{
HitThis();
}
}
In your method, you need to work with Response (HttpResponse) and after modifying the response, you need to end it (HttpResponse.End) so that normal page processing would not happen. If your method needs parameters then you have to pass them via form data and/or query string.

ASP.NET jQuery error: Unknown Web Method

This is my first time attempting to call an ASP.NET page method from jQuery. I am getting a status 500 error with the responseText message that the web method cannot be found. Here is my jQuery $.ajax call:
function callCancelPlan(activePlanId, ntLogin) {
var paramList = '{"activePlanId":"' + activePlanId + '","ntLogin":"' + ntLogin + '"}';
$.ajax({
type: "POST",
url: "ArpWorkItem.aspx/CancelPlan",
data: paramList,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() {
alert("success");
},
error: function(xml,textStatus,errorThrown) {
alert(xml.status + "||" + xml.responseText);
}
});
}
And here is the page method I am trying to call:
[WebMethod()]
private static void CancelPlan(int activePlanId, string ntLogin)
{
StrategyRetrievalPresenter presenter = new StrategyRetrievalPresenter();
presenter.CancelExistingPlan(offer, ntLogin);
}
I have tried this by decorating the Web Method with and without the parens'()'. Anyone have an idea?
Your web method needs to be public and static.
Clean the solution and rebuild. I've seen webmethods throw 500's until you do this.
Add public static before your method...
ex.
[WebMethod]
public static string MethodName() {}
For ajax success:
For me, it was helpful to make:
App_Start\RouteConfig
set
from
settings.AutoRedirectMode = RedirectMode.Permanent;
to
settings.AutoRedirectMode = RedirectMode.Off;
make your using method:
public
static
add:
using System.Web.Services;
and on top of method using just:
[WebMethod]
is enough
First Of All Don't Forget To Include
using System.Web.Services;
And Make Sure Your Method Should Be Public And Static and avoid adding Multiple Scripts in same Page like jquerymin.js shouldn't be used for every Function/Method in same Page
[WebMethod]
public static sting MethodName(){}
I Had The Same Issue Which Using Ajax And Jquery To Check Username Exists
Or Not.

Resources