简体   繁体   中英

How to call C# function from Javascript

I saw several solutions for this question. However when i tried myself it doesn't work well.

I tried to modify my C# code to this

[WebMethod]
protected void Show(object sender, EventArgs e)
{
    //C# function
}

But There is no WebMethod thing for my asp.net. Do I need to include some libraries?

In JS am I doing right? Why the sender and e are error?

 <script> $(document).ready(function () { var image = $("#VImage").html() $("#myModal").on("shown.bs.modal", function () { PageMethods.Show(object sender, EventArgs e); }); }); </script> 

You shouldn't call a function from anywhere like that, you are calling a function in the same fashion as declaring one.

PageMethods.Show(object sender, EventArgs e);

should be:

var sender, e;
PageMethods.Show(sender, e);

The way you're calling the C# method is no different than trying to make any other AJAX call. You just need to make sure that the C# method is properly exposed. To do that you need to.

  • Annotate it with [WebMethod]
  • Also believe it needs to be public and static in this case

On the client side, since you're using JQuery call it the same way you'd make any AJAX call

    $.ajax({
      type: "POST",
      url: "Default.aspx/Show",
      data: "{ sender: {}, e: {} }",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(msg) {
          console.log(msg);
      },
      error: function (msg) {
          console.log(msg);
      }
    });

Think of it this way, you need to make an HTTP request that includes all the information that the web server needs to know to invoke the C# method. This means it needs to be know the method name and the parameters that the method needs.

Behind the scenes when you make the HTTP request the framework is taking the body from the HTTP POST and attempting to deserialize the JSON object to get the name for the method and parameters it needs to invoke the C# method.

In your example the C# method has signature Show(object sender, EventArgs e) , that means the server is expecting from the client, two objects one of which it knows enough to deserialize into an EventArgs object so it can call the Show method.

I recommend changing the parameters to primitive types ('string', 'int', etc.) if possible or creating your own parameters object that you've verified that can be serialized/deserialized by .NET.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM