How to call server side method from JS
I've read a lot of questions, forums, blogs, tried a lot of things and I just can't get it to work.
I tried using PageMethods.MyMethod()
and it didn't work. I'm sure mine ScriptManager
had EnablePageMethods ="true"
and still nothing. I have a server side breakpoint and it never hits. Tried using ajax and nothing else
First of all I am trying to figure out how to make it work and then implement it in my program.
This is what I have tried so far:
server side:
[System.Web.Services.WebMethod]
public static void SomeMethod(string subject, string body, string recipients, string CurrentUserId)
{
MessageBox.Show("In c#");
}
JS:
function SomeFuntion()
{
debugger; alert("Before web service");
//PageMethods.CreateDraft(var1, var2, var3, var4);
$.ajax
(
{
type: "POST",
url: "NewMessage.aspx/SomeMethod",
data: "{subject:'" + var1+ "', body:'" + var2+ "', recipients:'" + var3
+ "', CurrentUserId:'" + var4+ "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function()
{
alert("In ajax");
}
}
);
}
As you can see, I tried PageMethods
it and it didn't work. I know the function is being triggered because I see a warning message. By the way, the function is called when the event is onclick
triggered by the button. I am not getting any errors or hitting a breakpoint on MessageBox
. This is new to me, so any explanation would be very helpful.
source to share
Check for errors on the server:
function SomeFuntion()
{
$.ajax({
type: "POST",
url: "NewMessage.aspx/CreateDraft",
data: "{subject:'" + var1+ "', body:'" + var2+ "', recipients:'" + var3+ "', CurrentUserId:'" + var4+ "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend:function ()
{
alert("about to send request");
},
success: function()
{
alert("In ajax");
},
error: function(xhr, status, error)
{
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
);
}
additional additions Since you are telling me that you are getting "HTTP POST HTTP address used to access path" ... "is not allowed" , you may need configuration to enable .NET web service for HTTP POST requests.
I lost .NET a few years ago and so I have no direct experience, but from what I could find on other sites, you might need to configure at the server level, like this:
<system.web>
<webServices>
<protocols>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
Or directives above your method like
[ScriptMethod(UseHttpPost = true)]
public string SomeMethod()
{
....
}
source to share
I was able to figure it out with the help of a friend, I would post my answer, but I find it quite long and complex. I understood most of what he did, but I still didn't believe how it worked. It was pretty much the same as me, but he did the JS in a separate file and set that file as base JS. Called a web service there and from my JS it called this function which calls the web service. And it worked lol
source to share