How to Call a C# Function from JavaScript

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# method from JavaScript with parameter

Create a web method. That's an easy and neat way of calling c# methods from Javascript. You can call that method using jQuery Ajax. See the below example for a webMethod.

[WebMethod]
public static string RegisterUser(string s)
{
//do your stuff
return stringResult;
}

and then call this method using jQuery ajax. You can pass parameters also. like given below

function showDetail(kurz) { 
String sParam = kurz.toString();
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{s:sParam}", // passing the parameter
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(retValue) {
// Do something with the return value from.Net method
}
});
}

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;

});

Call c# function through javascript

Taken from http://www.dotnetcurry.com/ShowArticle.aspx?ID=109&AspxAutoDetectCookieSupport=1 More ideas at Google Search

Step 1: Create an ASP.NET AJAX enabled website. Go to File > New > Website > ASP.NET AJAX-Enabled Web Site. Give the solution a name and location and click Ok.

Step 2: Drag and drop 2 labels and 4 textbox controls. We will be accepting the CustomerID from the user in the 2 textboxes and displaying the ‘ContactName’ in the other two textboxes. The textboxes that will display ‘ContactName’ has some properties set that will make it appear as a label without a border. Just set the BorderStyle=None, BorderColor=Transparent and ReadOnly=True. The markup will look similar to the following:

<form id="form1" runat="server">     

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

<div>

<asp:Label ID="lblCustId1" runat="server" Text="Customer ID 1"></asp:Label>

<asp:TextBox ID="txtId1" runat="server"></asp:TextBox><br />

<asp:TextBox ID="txtContact1" runat="server" BorderColor="Transparent" BorderStyle="None"

ReadOnly="True"></asp:TextBox><br />

<br />

<asp:Label ID="lblCustId2" runat="server" Text="Customer ID 2"></asp:Label>

 

<asp:TextBox ID="txtId2" runat="server"></asp:TextBox><br />

<asp:TextBox ID="txtContact2" runat="server" BorderColor="Transparent" BorderStyle="None"

ReadOnly="True"></asp:TextBox> <br />

</div>

</form>

Before moving ahead, we will store our connection string information in the Web.config. Add the following tag below your </configSections> tag. Remember we have created an ‘ASP.NET AJAX enabled website’. The tag </configSections> along with some other tags automatically get added to the web.config.

<connectionStrings>

<removename="all"/>

<addname="NorthwindConnectionString"connectionString="Data Source=(local); Initial Catalog=Northwind; Integrated Security = SSPI;"/>

</connectionStrings>

Step 3: Currently we will add a method, ‘GetContactName()’ which will accept a CustomerID and return the Contact Name information from the Northwind database, Customer table. We will then transform this method as a PageMethod.

C#

public static string GetContactName(string custid)

{

if (custid == null || custid.Length == 0)

return String.Empty;

SqlConnection conn = null;

try

{

string connection = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;

conn = new SqlConnection(connection);

string sql = "Select ContactName from Customers where CustomerId = @CustID";

SqlCommand cmd = new SqlCommand(sql, conn);

cmd.Parameters.AddWithValue("CustID", custid);

conn.Open();

string contNm = Convert.ToString(cmd.ExecuteScalar());

return contNm;

}

catch (SqlException ex)

{

return "error";

}

finally

{

conn.Close();

}

}

VB.NET

 Public Shared Function GetContactName(ByVal custid As String) As String

If custid Is Nothing OrElse custid.Length = 0 Then

Return String.Empty

End If

Dim conn As SqlConnection = Nothing

Try

Dim connection As String = ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString

conn = New SqlConnection(connection)

Dim sql As String = "Select ContactName from Customers where CustomerId = @CustID"

Dim cmd As SqlCommand = New SqlCommand(sql, conn)

cmd.Parameters.AddWithValue("CustID", custid)

conn.Open()

Dim contNm As String = Convert.ToString(cmd.ExecuteScalar())

Return contNm

Catch ex As SqlException

Return "error"

Finally

conn.Close()

End Try

End Function

Step 4: We will now transform this method as a PageMethod and then call this method GetContactName() from client side code; i.e. using JavaScript. To enable the method as a PageMethod, add the attribute [WebMethod] on top of the method:

C#

[System.Web.Services.WebMethod]

public static string GetContactName(string custid)

{

}

VB.NET

<System.Web.Services.WebMethod()> _

Public Shared Function GetContactName(ByVal custid As String) As String

End Function

At the sametime, add the attribute EnablePageMethods="true" to the ScriptManager as shown below:

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

Step 5: Let us now create the JavaScript that will call this server side code. Add a javascript file called script.js to your solution (Right Click Project > Add New Item > Jscript File > Rename file to script.js). Add the following code to the javascript file.

function CallMe(src,dest)

{

var ctrl = document.getElementById(src);

// call server side method

PageMethods.GetContactName(ctrl.value, CallSuccess, CallFailed, dest);

}

// set the destination textbox value with the ContactName

 function CallSuccess(res, destCtrl)

{

var dest = document.getElementById(destCtrl);

dest.value = res;

}

// alert message on some failure

function CallFailed(res, destCtrl)

{

alert(res.get_message());

}

Step 6: We now need to reference this JavaScript file from our aspx page and invoke the ‘CallMe()’ method whenever the textbox loses focus. To do so:

Add a reference to the javascript file in the body tag as shown below:

<body>

<script type="text/javascript" language="javascript" src="script.js"> </script>

<form id="form1" runat="server">

………

Step 7: To invoke the methods whenever the textbox looses focus, add these lines of code in the Page_Load() event

C#

if (!Page.IsPostBack)

{

txtId1.Attributes.Add("onblur", "javascript:CallMe('" + txtId1.ClientID + "', '" + txtContact1.ClientID + "')");

txtId2.Attributes.Add("onblur", "javascript:CallMe('" + txtId2.ClientID + "', '" + txtContact2.ClientID + "')");

}

VB.NET

If (Not Page.IsPostBack) Then

txtId1.Attributes.Add("onblur", "javascript:CallMe('" & txtId1.ClientID & "', '" & txtContact1.ClientID & "')")

txtId2.Attributes.Add("onblur", "javascript:CallMe('" & txtId2.ClientID & "', '" & txtContact2.ClientID & "')")

End If

As shown above, we are using the Attributes.Add that lets us add an attribute to the server control’s System.Web.UI.AttributeCollection object. The function ‘CallMe’ kept in the ‘script.js’ file will be invoked. We are passing the source and destination textboxes as parameters. The source textbox will contain the CustomerID. The CustomerID will be looked up in the Customers table and the corresponding ‘ContactName’ will be retrieved in the destination textbox.

Well that is all that is needed to invoke server side code from client side. Run the code. Type ‘ALFKI’ in the first textbox and hit the tab key. You will see that the javascript function goes ahead and calls the PageMethod GetContactName() using PageMethods.GetContactName. It passes the value of the source textbox which contains the CustomerID. The ‘ContactName’ returned is displayed in the second textbox below the first one, in our case the value displayed is ‘Maria Anders’.

Troubleshooting: ‘PageMethods Is 'Undefined'’ error

  1. Try setting EnablePageMethods="true" in the script manager tag

  2. Don't add the javascript references or code in the <head /> section. Add it to the <body> tag.





  3. Page methods needs to be static in code behind.

I hope you have got an idea of how to call server side code using JavaScript. I have used this technique successfully in a few projects and just love and admire PageMethods. I hope you found this article useful and I thank you for viewing it. The source code for this article can be downloaded from here.

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 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>

Call C# Method with JS

Create your method as a web-service (web-api is good) then call it using jS ajax, here's an example i use with web-api and JS (this is posting data, use get if you have nothing to post)

$.ajax({
type: 'Post',
contentType: "application/json; charset=utf-8",
url: "//localhost:38093/api/Acc/", //method Name
data: JSON.stringify({ someVar: 'someValue', someOtherVar: 'someOtherValue'}),
dataType: 'json',
success: someFunction(), // callback above
error: function (msg) {
alert(msg.responsetext);
}
});


Related Topics



Leave a reply



Submit