How to Call an ASP.NET C# Method Using JavaScript

how to call an ASP.NET c# method using javascript

PageMethod an easier and faster approach for Asp.Net AJAX
We can easily improve user experience and performance of web applications by unleashing the power of AJAX. One of the best things which I like in AJAX is PageMethod.

PageMethod is a way through which we can expose server side page's method in java script. This brings so many opportunities we can perform lots of operations without using slow and annoying post backs.

In this post I am showing the basic use of ScriptManager and PageMethod. In this example I am creating a User Registration form, in which user can register against his email address and password. Here is the markup of the page which I am going to develop:

<body>
<form id="form1" runat="server">
<div>
<fieldset style="width: 200px;">
<asp:Label ID="lblEmailAddress" runat="server" Text="Email Address"></asp:Label>
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
<asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
</fieldset>
<div>
</div>
<asp:Button ID="btnCreateAccount" runat="server" Text="Signup" />
</div>
</form>
</body>
</html>

To setup page method, first you have to drag a script manager on your page.

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>

Also notice that I have changed EnablePageMethods="true".
This will tell ScriptManager that I am going to call PageMethods from client side.

Now next step is to create a Server Side function.
Here is the function which I created, this function validates user's input:

[WebMethod]
public static string RegisterUser(string email, string password)
{
string result = "Congratulations!!! your account has been created.";
if (email.Length == 0)//Zero length check
{
result = "Email Address cannot be blank";
}
else if (!email.Contains(".") || !email.Contains("@")) //some other basic checks
{
result = "Not a valid email address";
}
else if (!email.Contains(".") || !email.Contains("@")) //some other basic checks
{
result = "Not a valid email address";
}

else if (password.Length == 0)
{
result = "Password cannot be blank";
}
else if (password.Length < 5)
{
result = "Password cannot be less than 5 chars";
}

return result;
}

To tell script manager that this method is accessible through javascript we need to ensure two things:
First: This method should be 'public static'.
Second: There should be a [WebMethod] tag above method as written in above code.

Now I have created server side function which creates account. Now we have to call it from client side. Here is how we can call that function from client side:

<script type="text/javascript">
function Signup() {
var email = document.getElementById('<%=txtEmail.ClientID %>').value;
var password = document.getElementById('<%=txtPassword.ClientID %>').value;

PageMethods.RegisterUser(email, password, onSucess, onError);

function onSucess(result) {
alert(result);
}

function onError(result) {
alert('Cannot process your request at the moment, please try later.');
}
}
</script>

To call my server side method Register user, ScriptManager generates a proxy function which is available in PageMethods.
My server side function has two paramaters i.e. email and password, after that parameters we have to give two more function names which will be run if method is successfully executed (first parameter i.e. onSucess) or method is failed (second parameter i.e. result).

Now every thing seems ready, and now I have added OnClientClick="Signup();return false;" on my Signup button. So here complete code of my aspx page :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<fieldset style="width: 200px;">
<asp:Label ID="lblEmailAddress" runat="server" Text="Email Address"></asp:Label>
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
<asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
</fieldset>
<div>
</div>
<asp:Button ID="btnCreateAccount" runat="server" Text="Signup" OnClientClick="Signup();return false;" />
</div>
</form>
</body>
</html>

<script type="text/javascript">
function Signup() {
var email = document.getElementById('<%=txtEmail.ClientID %>').value;
var password = document.getElementById('<%=txtPassword.ClientID %>').value;

PageMethods.RegisterUser(email, password, onSucess, onError);

function onSucess(result) {
alert(result);
}

function onError(result) {
alert('Cannot process your request at the moment, please try later.');
}
}
</script>

How to call C# class method using Javascript?

I don't thing you can do that because:

  • ASPX is server side, whereas JavaScript is client side
  • some components from a ASP site are compiled

What you can do is expose a route (if you were using MVC desing pattern) on the server that calls that function (or an Api for that mather).

How to call C# method from Javascript in ASP.NET Core?

I see you're using Razor pages. A method in razor page model is not a routed method (it can't be called by requesting a route), and that's why trying to send an ajax request to Index\FindUser won't work, and the error returned by server would be 404 not found.

Alternatively you can use razor page handlers.

In your Index.cshtml.cs rename the method FindUser() to OnGetFindUser() or OnGetFindUserAsync() if the method is an asynchronous method.

You can then call this method by sending a request to "Index?handler=FindUser".

// Note the difference in method name
public IActionResult OnGetFindUser()
{
return new JsonResult("Founded user");
}
function findUsers() {
$.ajax({
type: 'GET',
// Note the difference in url (this works if you're actually in Index page)
url: '?handler=FindUser',
success: function (data) {
alert(data);
},
error: function (error) {
alert("Error: " + error);
}
})
}

Further suggested read

How to call c# function from js function inside asp.net?

the c# method should be a webmethod .

[WebMethod]

here goes your c# method

you need to import system.web.services into your code first ,

using System.Web.Services;

and write the js function into the form submit event ( if you cant access submit button)

write onsubmit="yourfun()" inline in the form

or if you are using jquery

$("#form-id").submit(function(){

your function;

});

How to call a C# function from JavaScript?

You can use a Web Method and Ajax:

<script type="text/javascript">             //Default.aspx
function DeleteKartItems() {
$.ajax({
type: "POST",
url: 'Default.aspx/DeleteItem',
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#divResult").html("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
});
}
</script>

[WebMethod] //Default.aspx.cs
public static void DeleteItem()
{
//Your Logic
}

Call C# Function From JavaScript/JQuery In Asp.net webforms

You can use __doPostBack from the script, and use the RaisePostBackEvent method in the code behind to perform your server-side logic. If you're looking to do a redirect, this would probably be the best way.

EDIT

If you're looking to do some validation in JavaScript when a button is clicked, use OnClientClick to perform your JavaScript validation, and return true if the validation succeeds.

<asp:Button ID="Button1" runat="server" OnClientClick="return validateStuff();" OnClick="Button1_Click" />

Your JavaScript validation:

validateStuff = function(){
var isValid = true;
var txt = document.getElementById("<%=TextBox1.ClientID%>");
if (txt.value.toLower() != "james"){
isValid = false;
}
return isValid;
}

If the validateStuff function returns true, a postback will occur and you can handle your save/update logic in the button click event:

protected void Button1_Click(object sender, EventArgs e)
{
//save some stuff to the database

string txtValue = TextBox1.Text.Trim();
}

In JavaScript:

redirectToAnotherPage = function(){
__doPostBack("<%=SomeServerControl.ClientID%>", "someArgument");
}

In the code-behind:

protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
//call the RaisePostBack event
base.RaisePostBackEvent(source, eventArgument);

Response.Redirect("anotherpage.aspx");
}

If all you're looking to do is bring the user to another page, you can also do this:

redirectToAnotherPage = function(){
window.location.href = "somepage.aspx";
}

Call ASP.NET function from JavaScript?

Well, if you don't want to do it using Ajax or any other way and just want a normal ASP.NET postback to happen, here is how you do it (without using any other libraries):

It is a little tricky though... :)

i. In your code file (assuming you are using C# and .NET 2.0 or later) add the following Interface to your Page class to make it look like

public partial class Default : System.Web.UI.Page, IPostBackEventHandler{}

ii. This should add (using Tab-Tab) this function to your code file:

public void RaisePostBackEvent(string eventArgument) { }

iii. In your onclick event in JavaScript, write the following code:

var pageId = '<%=  Page.ClientID %>';
__doPostBack(pageId, argumentString);

This will call the 'RaisePostBackEvent' method in your code file with the 'eventArgument' as the 'argumentString' you passed from the JavaScript. Now, you can call any other event you like.

P.S: That is 'underscore-underscore-doPostBack' ... And, there should be no space in that sequence... Somehow the WMD does not allow me to write to underscores followed by a character!

Calling C# Function from ASP.NET View

One line answer: MVC doesn't work like that.

Longer answer: You can't access the server-side code directly from the browser like that. The most common solution is to use something called AJAX to call the C# function on the server. You then need to write code in the View to handle the response from the server. Have a look at this question and this answer: https://stackoverflow.com/a/16186212/5173105

How do I call a JavaScript function from Asp.Net Code Behind?

By default, the script is written to the output but without the <script> tags. You probably would have noticed this if you were using your browser's JavaScript console or looking at the resulting HTML on the client. Make sure you familiarize yourself with those tools.

You can have it add the script tags for you with a slightly different overload of the method.

Page.ClientScript.RegisterStartupScript(this.GetType(), "MyKey", "WantToSave();", true);

Or you can add them yourself:

Page.ClientScript.RegisterStartupScript(this.GetType(), "MyKey", "<script>WantToSave();</script>");

The combination of the key string and the type the control was registered with serve to uniquely identify the registered script, in case you later want to unregister it or replace it with a different script. So the key doesn't have to be anything specific, just something unique.



Related Topics



Leave a reply



Submit