How to call a C# function from JavaScript?
Asked Answered
H

8

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?

Hocker answered 26/8, 2013 at 9:44 Comment(4)
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.Quern
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 .Imbricate
you should be using Ajax LibraryDoggoned
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!!Hocker
R
40

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
}
Rectangle answered 20/6, 2014 at 19:40 Comment(2)
your example calls the c# code page, not the function.Thermophone
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?Marchak
M
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

Militiaman answered 25/4, 2016 at 8:17 Comment(2)
if you do not find your function, try making it static.Sse
how do you process the return value?Marchak
E
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

Ehudd answered 13/3, 2018 at 15:10 Comment(0)
G
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)
}
Guthrun answered 25/6, 2018 at 22:43 Comment(0)
D
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

Doggoned answered 26/8, 2013 at 9:50 Comment(0)
I
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.

Insouciant answered 26/8, 2013 at 9:49 Comment(0)
C
0
   I have written this code to get state by country for examples
  $(document).ready(function () {
    alert('test');
    $("#City_CountryId").change(function () {
        var countryId = $(this).val();
        $.ajax({
            url: '@Url.Action("GetStatesByCountry", "City")',
            type: 'GET',
            //dataType: 'json'
            data: { countryId: countryId },
            success: function (data) {
                $("#City_StateId").empty();
                $("#City_StateId").append('<option disabled selected>--Select State--</option>');
               // alert(data);
                $.each(data, function (i, state) {
                   // alert(i);
                    $("#City_StateId").append($('<option></option>').val(state.id).text(state.stateName));
                });
            }
        });
    });
Carlisle answered 29/2 at 10:27 Comment(0)
K
-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.

Kosse answered 26/8, 2013 at 9:45 Comment(2)
daniweb.com/web-development/aspnet/threads/31065/… hereStendhal
@Shyamsundarshah which describes AJAX and __doPostback, which basically are ways to trigger the server to run something. But in a sense, you are right.Kosse

© 2022 - 2024 — McMap. All rights reserved.