In this article I will explain with an example, how to call Controller’s Action method from ReactJS in ASP.Net Core MVC.
The Controller’s Action method will be called using AJAX with the help of XmlHttpRequest (XHR) function inside the ReactJS class.
 
 
Software Information
This article makes use of Visual Studio 2019, MVC Core and .Net Core 3.1.
 
 
Integrating ReactJS with ASP.Net Core MVC
For more information on integrating ReactJS with ASP.Net Core MVC, please refer my article ASP.Net Core: ReactJS Hello World Example.
 
 
Configuring the JSON Serializer setting
The first step is to configure the JSON Serializer settings in the Startup.cs file.
1. Open the Startup.cs class from the Solution Explorer window.
ASP.Net Core: Call Controller Action method from ReactJS
 
2. Then inside the ConfigureServices method, you will have to add the following code which will instruct the program to use JSON serialization.
publicvoid ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews()
        .AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);
}
 
 
Model
Following is a Model class named PersonModel with two properties i.e. Name and DateTime.
public class PersonModel
{
    ///<summary>
    /// Gets or sets Name.
    ///</summary>
    public string Name { get; set; }
 
    ///<summary>
    /// Gets or sets DateTime.
    ///</summary>
    public string DateTime { get; set; }
}
 
 
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
 
Action method for handling XmlHttpRequest (XHR) AJAX operation
This Action method handles the AJAX call made from the XmlHttpRequest (XHR) function inside the ReactJS class.
Note: The following Action method handles AJAX calls and hence the return type is set to JsonResult.
 
The object of PersonModel class is received as parameter and the Name property holds the value of the TextBox sent from the XmlHttpRequest (XHR) function.
Note: The FromBody attribute is used for model-binding the data sent from XmlHttpRequest (XHR) request.
 
Finally, the Current DateTime of the Server is set into the DateTime property and the PersonModel object is returned back as JSON to the XmlHttp Request (XHR) function inside the ReactJS class.
public class HomeController : Controller
{
    // GET: Home
    public IActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public JsonResult AjaxMethod([FromBody] PersonModel person)
    {
        person.DateTime = DateTime.Now.ToString();
        return Json(person);
    }
}
 
 
ReactJS JSX file
Following is the ReactAJAX class which extends ReactJS Component.
 
Constructor
Inside the Constructor, a variable Name is declared and assigned to the state.
Finally, the event handlers for the OnChange and OnClick i.e. updateName and handleClick respectively are bound.
 
Render function
The Render function returns an HTML TextBox and a Button element. The TextBox has been assigned with an OnChange event handler while the Button has been assigned with an OnClick event handler.
 
Event Handlers
OnChange
When the contents of the TextBox are changed, the updateName event handler is triggered and it sets the value of the TextBox in the Name variable of the state using the setState function.
 
OnClick
When the Button is clicked, an XmlHttpRequest (XHR) AJAX request is made to the Controller’s Action method and the value of the Name variable is sent to it.
The received response i.e. the Name and the Current DateTime is displayed in JavaScript Alert Message Box.
Finally, the ReactDOM.render function, render’s the class in a HTML DIV with ID dvMessage.
class ReactAJAX extends React.Component {
    constructor(props) {
        super(props);
        this.state = { Name: "" };
 
        this.updateName = this.updateName.bind(this);
        this.handleClick = this.handleClick.bind(this);
    }
    updateName(e) {
        this.setState({ Name: e.target.value });
    }
    handleClick() {
        var request;
        if (window.XMLHttpRequest) {
            //New browsers.
            request = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            //Old IE Browsers.
            request = new ActiveXObject("Microsoft.XMLHTTP");
        }
        if (request != null) {
            request.open("POST", "/Home/AjaxMethod", false);
            var params = "{name: '" + this.state.Name + "'}";
            request.setRequestHeader("Content-Type", "application/json");
            request.onload = function () {
                if (request.readyState == 4 && request.status == 200) {
                    var response = JSON.parse(request.responseText);
                    alert("Hello: " + response.Name + " .\nCurrent Date and Time: " + response.DateTime);
                }
            }.bind(this);
            request.send(params);
        }
    }
  
    render() {
        return (
            <div>
               <input type="text" onChange={this.updateName}></input>&nbsp;
               <input type="button" onClick={this.handleClick} value="Get Current Time"></input>
            </div>
        );
    }
}
 
ReactDOM.render(
    <ReactAJAX />,
    document.getElementById('dvMessage')
);
 
 
View
The View consists of an HTML DIV dvMessage inside which the message from the ReactJS will be displayed.
Then the following necessary JS files for ReactJS application are inherited.
1. react.development.js
2. react-dom.development.js
Finally, the ReactAJAX.jsx file is inherited.
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div id="dvMessage"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.development.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.development.js"></script>
    <script src="@Url.Content("~/Scripts/ReactAJAX.jsx")"></script>
</body>
</html>
 
That’s it and the application is ready to run.
 
 
Screenshot
ASP.Net Core: Call Controller Action method from ReactJS
 
 
Downloads