J. Raj
J. Raj

Reputation: 55

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();
        }
    }
}

Upvotes: 0

Views: 842

Answers (2)

Benjamin RD
Benjamin RD

Reputation: 12034

. 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!");
  });
});

Upvotes: 0

D-Shih
D-Shih

Reputation: 46229

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

Upvotes: 4

Related Questions