ajax request Mootools to asp.net webforms - asp.net

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.

Related

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.

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

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";
}

IHttpModule is not being called for my WebMethod

Ok, so I have an existing application to which I have added a custom HttpModule. I'm registering two events in the Init() method (PreRequestHandlerExecute and PostRequestHandlerExecute). The HttpModule gets called for every 'normal' request. But not I have created an .aspx containing a few WebMethods that are being called for ajaxifying some UI components. The WebMethod gets called nicely, but the trouble is that my HttpModule does NOT get called at all (no events, no init, even no constructor) when accessing the WebMethod. The module gets called nicely when accessing the .aspx in question as a 'normal' request. But it refuses to be called when calling the WebMethod.
My .aspx looks like this:
public partial class SelectionListService : System.Web.UI.Page
{
[WebMethod]
[ScriptMethod]
public static RadComboBoxData GetItemsAsRadComboBoxData(RadComboBoxContext context)
{
...
}
}
My HttpModule look like this:
public class MyModule : IHttpModule, IRequiresSessionState
{
public MyModule ()
{
}
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += new EventHandler(Application_PreRequestHandlerExecute);
context.PostRequestHandlerExecute += new EventHandler(Application_PostRequestHandlerExecute);
}
private void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
...
}
private void Application_PostRequestHandlerExecute(object sender, EventArgs e)
{
...
}
}
I have been digging into this for quite some time now, but I just can't get it to work. Any ideas?
PS1: the BeginRequest, etc in global.asax.cs do get called when accessing the WebMethod.
PS2: I'm running IIS7 on Windows7.
since PageMethods must be static, an instance of the Page class with all it's events and the ASP.NET pipeline never happens. You simply get the result of your PageMethod call, and that is all.
I have a project that had the same problem. We found that the first event in the pipeline that we could get to fire for the WebMethods was the AcquireRequestState event. We hooked into that with our HttpModule in order to do the authorization checking required for the application.
I don't know what your pre and post request handlers do, but maybe you could shift some of the logic into the AcquireRequestState event handler.

jQuery post to method in class

I am in a legacy asp.net application and I need to call a method within a class via jQuery ajax post.
So far I have a class called NewClass with a single method;
[WebMethod]
public string jQuery_GetCategoryDescription(string CategoryName)
{
return "Slappy";
}
I then have the following jQuery;
$.post('/NewClass/jQuery_GetCategoryDescription', { CategoryName: "trippy" }, function (newHTML) {
alert(newHTML);
});
I've tried putting in the whole namespace in.
However I can't seem to call the method within the class.
EDIT
I am getting a 405 error
If the
[WebMethod]
public string jQuery_GetCategoryDescription(string CategoryName)
{
return "Slappy";
}
Is in side Index.aspx
You can call it by /Index.aspx/jQuery_GetCategoryDescription

Is it possible to launch an event from a Silverlight control that can be used in your asp.net page?

Curious how this could be done. Is there any way to create a delegate method within a Silverlight control that can be used within an Asp.net page that the control resides?
For example, let's say you are creating a Silverlight control that solicits information from a user (Ie. Name, age, etc), is there a way to somehow bind to a click event on the Silverlight control from the asp.net page it is sitting on, and then get the information from that Silverlight control?
It is possible to do what you ask, but it doesn't have much to do with ASP.Net. Since Silverlight runs on the client you would just have the click event in Silverlight update the html content. You could then send that data back to the ASP.Net when you do a postback.
Unless you have a good reason to do this, it probably isn't the best approach. You'd probably be better of sending the data back to the webserver using a web service instead of going through ASP.Net.
I done that registering a Javascript event and manually calling back my server controls. Some important pieces below:
<asp:Silverlight runat="server" ID="SilverlightUpload"
Source="~/ClientBin/Silverlight.xap" OnPluginLoaded="pluginLoaded" />
<asp:Button runat="server" OnClientClick="return cancelUpload()" Text="Cancel" />
<script type="text/javascript">
var uploadControl = null;
function pluginLoaded(sender) {
uploadControl = sender.get_element().content.uploadControl;
uploadControl.addEventListener("OnFileListChanged", onFileListChanged);
}
function onFileListChanged(sender, e) {
var files = [];
for (var i = 0; i < e.Files.length; i++) {
files[i] = {
Id : e.Files[i].Id,
Name : e.Files[i].Name
};
}
__doPostBack("<%= RadGrid1.UniqueID %>",
"OnFileListChanged:" + JSON.stringify(files));
}
function cancelUpload() {
$find("<%= SilverlightUpload.ClientID %>")
.get_element().content.uploadControl.StopUpload();
return false;
}
</script>
And Silverlight codebehind:
[ScriptableType] // MUST
public partial class Page : UserControl
{
[ScriptableMember] // MUST
public event EventHandler<FileListChangedEventArgs> OnFileListChanged;
[ScriptableMember] // MUST
public void StopUpload() { }
}
[ScriptableType]
public class FileListChangedEventArgs : EventArgs
{
public FileUploadItem[] Files { get; internal set; }
}
[DataContract]
[ScriptableType]
public class FileUploadItem
{
}

Resources