📜  ajax asp.net core - C# (1)

📅  最后修改于: 2023-12-03 15:29:18.747000             🧑  作者: Mango

AJAX in ASP.NET Core using C#

What is AJAX?

AJAX (Asynchronous JavaScript and XML) is a technique used in web development to create dynamic, responsive and interactive user interfaces. AJAX allows web applications to make asynchronous requests to the server and update the content of a web page without refreshing the entire page.

AJAX in ASP.NET Core

In ASP.NET Core, AJAX can be implemented using jQuery and the $.ajax() method. This method allows you to send an HTTP request to the server asynchronously and handle the response using callback functions.

Here is an example of how to use the $.ajax() method in ASP.NET Core:

$.ajax({
  type: "POST",
  url: "/Home/Add",
  data: { num1: 10, num2: 20 },
  success: function(result) {
    $("#result").text(result);
  },
  error: function(error) {
    console.log(error);
  }
});

In this example, we are sending a POST request to the /Home/Add URL with two parameters, num1 and num2, which have values of 10 and 20 respectively. Additionally, we have specified two callback functions, success and error, to handle the response from the server.

Implementing AJAX in ASP.NET Core using C#

To implement AJAX in ASP.NET Core using C#, you can create a controller method that returns a JSON object containing the data that needs to be updated on the web page. You can then use jQuery to send an AJAX request to this method and update the HTML using the data returned by the controller.

Here is an example of how to create a controller method that returns JSON data:

[HttpPost]
public IActionResult GetData()
{
    var data = new { Name = "John Doe", Age = 30 };
    return Json(data);
}

In this example, we are creating a method that returns a JSON object containing the name and age of a person.

To send an AJAX request to this method and update the HTML using the data returned, you can use the following code:

$.ajax({
  type: "POST",
  url: "/Home/GetData",
  success: function(result) {
    $("#name").text(result.Name);
    $("#age").text(result.Age);
  },
  error: function(error) {
    console.log(error);
  }
});

In this code, we are sending a POST request to the /Home/GetData URL and updating the HTML using the data returned by the controller method.

Conclusion

In conclusion, AJAX is a powerful technique that can be used to create dynamic and interactive user interfaces in ASP.NET Core using C#. By using jQuery and the $.ajax() method, you can easily send asynchronous requests to the server and update the content of a web page without refreshing the entire page.