Hello everyone I have faced an issue I have call a ajax with razor .net core.
public void OnGet() This is my GetFunction
{
}
I have called this function by ajax It's called successfully. But I have called a Public void OnPost() not called this by ajax.
$.ajax({
type: "POST", -- Not Called
url: "/Shared/_Partial?handler=InsertEmailBlastDetails",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: record,
success: function (data) {
}
$.ajax({
type: "GET", -- Called
url: "/Shared/_Partial?handler=InsertEmailBlastDetails",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: record,
success: function (data) {
}
Tuhin PaulPosted May 21, 2023, 2:12 PM
Part 3
3. Consider using the `done()` and `fail()` methods instead of the `success` and `error` callbacks for the Ajax request. This allows for cleaner code and better error handling.
These optimizations can help improve the readability, maintainability, and security of your code.
Tuhin PaulPosted May 21, 2023, 2:11 PM
Part 2
2. If you are using ASP.NET Core, consider using the `ValidateAntiForgeryToken` attribute on your `OnPost` method to protect against CSRF attacks. You will need to generate and include an anti-forgery token in your Ajax request. Here's an example of how to do it:
Tuhin PaulPosted May 21, 2023, 2:10 PM
Based on the given code snippet, please check my comments:
Part 1
1. Use the `@Url.Action` helper method to generate the URL for the Ajax request. This way, you can avoid hard-coding the URL and ensure that the correct URL is used even if the application's routing configuration changes.
Tuhin PaulPosted May 21, 2023, 2:07 PM
The reason why your OnPost() method is not being called by Ajax is because you are using the GET method instead of the POST method. The GET method is used to retrieve data from a server, while the POST method is used to send data to a server. In your case, you are trying to send data to the server, so you need to use the POST method.
To fix this, change the type of your Ajax request to POST:
Once you have made this change, your OnPost() method should be called when you submit the Ajax request.
Mudzakkir TohaPosted May 21, 2023, 1:35 PM
based on this post, you should rename OnPost method into
OnPostInsertEmailBlastDetailsAsynchttps://www.learnrazorpages.com/razor-pages/handler-methods
Rajkiran SwainPosted May 16, 2023, 10:56 AM
Try changing the URL in your AJAX call to include the handler name for the OnPost method:
Also make sure that you have a method named "InsertEmailBlastDetailsOnPost" with the [HttpPost] attribute in your Razor page.