How to get data from Ajax request in controller

To get data from an Ajax request in a controller, you can use the `[FromBody]` attribute to bind the data to a parameter in the controller method.

Here's an example of how to do this in C#:

[HttpPost]
public IActionResult MyActionMethod([FromBody] MyModel model)
{
    // Use the model data
    return View();
}

In this example, the `[HttpPost]` attribute specifies that the method should be invoked when an HTTP POST request is made to the server. The `[FromBody]` attribute specifies that the `model` parameter should be populated with the data in the request body.

`MyModel` is a class that you define to represent the data being sent from the client. The properties in this class should match the names and types of the data being sent from the client. For example, if you are sending a JSON object with two properties called `name` and `age`, your `MyModel` class would look something like this:

public class MyModel
{
    public string Name { get; set; }
    public int Age { get; set; }
}

You can then use the `model` parameter in your controller method to access the data sent from the client.

If you are sending a simple data type like a string or integer, you can use that data type as the parameter type in your controller method. For example:

[HttpPost]
public IActionResult MyActionMethod([FromBody] string value)
{
    // Use the value
    return View();
}

In this example, the `[FromBody]` attribute specifies that the `value` parameter should be populated with the data in the request body, which is expected to be a string. You can then use the `value` parameter in your controller method to access the data sent from the client.
Previous Post Next Post