AJAX Calls to Controllers in ASP.NET MVC
When working with ASP.NET MVC, AJAX calls allow you to send data to and receive data from a server without reloading the entire page. Here's a detailed explanation of making a simple AJAX call to a controller:
Code Breakdown
Controller:
The controller contains the FirstAjax method, which returns JSON data (in this case, the string "chamara").
View:
Problem
Initially, the AJAX call was not firing an alert because the data attribute was not removed. The controller did not expect any parameters, so removing the data solved the issue.
Modified Controller
In the updated controller, two FirstAjax methods were added to demonstrate both GET and POST scenarios. POST requires a parameter, but it is not used in this example.
Working AJAX Call
The final working AJAX call uses Razor syntax to dynamically generate the URL and removes the unnecessary data attribute:
$.ajax({ type: "POST", url: '@Url.Action("FirstAjax", "AjaxTest")', contentType: "application/json; charset=utf-8", dataType: "json", success: successFunc, error: errorFunc });
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3