31

I want to call CsharpFunction, a C# function in code-behind, from JavaScript. I tried the code below but whether the JavaScript condition is True or False, CsharpFunction was called regardless!

JavaScript code:

if (Javascriptcondition > 0) {
   <%CsharpFunction();%>
}

C# code behind:

protected void CsharpFunction()
{
  // Notification.show();
}

How do I call a C# function from JavaScript?

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
IamNumber5
  • 351
  • 1
  • 3
  • 9
  • 2
    The way you did it is wrong. The code you have written is executed on the server and the server does not know about your javascript condition. You might want to use AJAX. – Nilesh Aug 26 '13 at 09:46
  • Sorry for half baked answer ! Well you can send your condition with form in hidden fields and than you can check its value for calling that method or not . – Suraj Singh Aug 26 '13 at 09:53
  • you should be using Ajax Library – Rohit Aug 26 '13 at 09:55
  • Thanks all for such a helpfull comment! I appreciate your effort thanks a lot! but can anyone please give me an example how to use ajax!! – IamNumber5 Aug 26 '13 at 10:57

7 Answers7

39

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
}
Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
user3098137
  • 511
  • 4
  • 7
  • 4
    your example calls the c# code page, not the function. – vico Jun 20 '14 at 20:04
  • I like this solution, but the default IIS/ASP.NET permissions don't allow `$.ajax(...)` to call the controller without authentication (which is nice). Isn't there an easy way to call the controller without having to lower the security of the page? – tresf Oct 31 '19 at 17:57
8
.CS File    
    namespace Csharp
    {
      public void CsharpFunction()
      {
        //Code;
      }
    }

    JS code:
    function JSFunction() {
            <%#ProjectName.Csharp.CsharpFunction()%> ;
    }

Note :in JS Function when call your CS page function.... first name of project then name of name space of CS page then function name

Vijay Mungara
  • 83
  • 1
  • 5
4

A modern approach is to use ASP.NET Web API 2 (server-side) with jQuery Ajax (client-side).

Like page methods and ASMX web methods, Web API allows you to write C# code in ASP.NET which can be called from a browser or from anywhere, really!

Here is an example Web API controller, which exposes API methods allowing clients to retrieve details about 1 or all products (in the real world, products would likely be loaded from a database):

public class ProductsController : ApiController
{
    Product[] products = new Product[] 
    { 
        new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, 
        new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, 
        new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } 
    };

    [Route("api/products")]
    [HttpGet]
    public IEnumerable<Product> GetAllProducts()
    {
        return products;
    }

    [Route("api/product/{id}")]
    [HttpGet]
    public IHttpActionResult GetProduct(int id)
    {
        var product = products.FirstOrDefault((p) => p.Id == id);
        if (product == null)
        {
            return NotFound();
        }
        return Ok(product);
    }
}

The controller uses this example model class:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Category { get; set; }
    public decimal Price { get; set; }
}

Example jQuery Ajax call to get and iterate over a list of products:

$(document).ready(function () {
    // Send an AJAX request
    $.getJSON("/api/products")
        .done(function (data) {
            // On success, 'data' contains a list of products.
            $.each(data, function (key, item) {
                // Add a list item for the product.
                $('<li>', { text: formatItem(item) }).appendTo($('#products'));
            });
        });
});

Not only does this allow you to easily create a modern Web API, you can if you need to get really professional and document it too, using ASP.NET Web API Help Pages and/or Swashbuckle.

Web API can be retro-fitted (added) to an existing ASP.NET Web Forms project. In that case you will need to add routing instructions into the Application_Start method in the file Global.asax:

RouteTable.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = System.Web.Http.RouteParameter.Optional }
);

Documentation

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
3

Use Blazor http://learn-blazor.com/architecture/interop/

Here's the C#:

namespace BlazorDemo.Client
{
   public static class MyCSharpFunctions
   {
       public static void CsharpFunction()
       {
          // Notification.show();
       }
   }
}

Then the Javascript:

const CsharpFunction = Blazor.platform.findMethod(
"BlazorDemo.Client",
"BlazorDemo.Client",
"MyCSharpFunctions",
"CsharpFunction"
);
if (Javascriptcondition > 0) {
   Blazor.platform.callMethod(CsharpFunction, null)
}
Patrick Knott
  • 1,666
  • 15
  • 15
1

Server-side functions are on the server-side, client-side functions reside on the client. What you can do is you have to set hidden form variable and submit the form, then on page use Page_Load handler you can access value of variable and call the server method.

More info can be found here and here

Community
  • 1
  • 1
Rohit
  • 10,056
  • 7
  • 50
  • 82
0

If you're meaning to make a server call from the client, you should use Ajax - look at something like Jquery and use $.Ajax() or $.getJson() to call the server function, depending on what kind of return you're after or action you want to execute.

Russell Young
  • 2,033
  • 1
  • 14
  • 12
-5

You can't. Javascript runs client side, C# runs server side.

In fact, your server will run all the C# code, generating Javascript. The Javascript then, is run in the browser. As said in the comments, the compiler doesn't know Javascript.

To call the functionality on your server, you'll have to use techniques such as AJAX, as said in the other answers.

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
  • http://www.daniweb.com/web-development/aspnet/threads/31065/calling-c-function-through-javascript-in-asp.net here – Shyam sundar shah Aug 26 '13 at 09:47
  • 2
    @Shyamsundarshah which describes AJAX and `__doPostback`, which basically are ways to trigger the server to run something. But in a sense, you are right. – Bart Friederichs Aug 26 '13 at 09:54