Need to call code behind method from Javascript without using ajax in asp.net
Add following HTML on page:
<asp:ScriptManager ID='ScriptManager1' runat='server' EnablePageMethods='true' />
<asp:Button ID=”btnSave” runat=”server” Text=”Save” OnClientClick=”return CodeBehindMethodCall();” />
Now time to adjust our code behind so we can call it from JavaScript, we need to use System.Web.Services so add it in our code behind file
using System.Web.Services;
Whatever method we need to call from JavaScript, add WebMethodattribute to that method and that will easily be called by javaScript
[WebMethod]
public String ConvertDataTabletoString()
{
// your code
}
Now we will call ConvertDataTabletoString from JavaScript, so add the following JavaScript to the page:
function CodeBehindMethodCall()
{
pageName.ConvertDataTabletoString();
}
As you can see we have not used web service but we changed a method to web method so it can be called from JavaScript but without converting a method into web method we can not call any code behind method from JavaScript.
This is how its done.
Sunil Prabakar
Updated on June 28, 2022Comments
-
Sunil Prabakar almost 2 years
I need to call server side method in code behind file from javascript. Yes i know ajax is the best way to achieve this. But i am not able to use ajax bcoz i exported excel file and get download in server side method. In ajax request we not are able to download/upload files. So kindly suggest any other way to call server side method in code behind from client side. I am also able to achieve this using web service. But i need the functionality in code behind file. I need the functionality like MVC form, in mvc form we are able to give control and action name and make form submit.