简体   繁体   中英

Call C# method on button click using JavaScript/jQuery

I am trying to call a C# function on a button click using JavaScript/jQuery function.

I went through similar issues and their solutions, but none fits this case. My C# function does not return anything. It's a function that triggers a job from the task scheduler. Is there a different way to write the JavaScript function, where the function does not return anything?

Below is the code.

HTML:

<button id="btnClick" runat="server" EnablePageMethods="true">Replay</button>

JavaScript:

$(document).ready(function() {
  $(".btnClick").on('click', function() {
    $.ajax({
      async: true,
      url: "Home/ABVReplay",
      cache: false,
    });
    console.log("Replayed!");
  });
});

C#:

[WebMethod]
public void ABVReplay()
{
    using (TaskService tasksrvc = new TaskService("<server.name>", "<username>", "<domain>", "<password>"))
    {
        Task task = tasksrvc.FindTask("<taskName>");
        task.Run();
    }

}

The job runs if I just use the C# code in a console application. So, there is no connection/login issue as such.

Console app code:

using System;
using Microsoft.Win32.TaskScheduler;

class Program
{
    static void Main(string[] args)
    {
        using (TaskService tasksrvc = new TaskService("<server.name>", "<username>", "<domain>", "<password>"))
        {
            Task task = tasksrvc.FindTask("<taskName>");
            task.Run();
        }
    }
}

Your jquery selector need to change

$("#btnClick")

instead of

$(".btnClick")

and make sure your call URL is correct.

# select html tag id

. select html tag class

. represents jquery class and # represents id , you have to replace for this code, and should works.

$(document).ready(function () {
  $("#btnClick").on('click', function () {

    $.ajax({
        async: true,
        url: "Home/ABVReplay",
        cache: false,
     });
    console.log("Replayed!");
  });
});

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