I was trying to delete an individual row from jQuery data-table based on the userID
by making the AJAX call from my jQuery and then calling my action method DisableUser(int userID)
. When I'm redirected to the view, I get an error.
Here is my jQuery code:
$('#usersList').on('click', 'button[id^="delete_"]', function () {
var userId = this.id.replace("delete_", "");
$.ajax({
type: 'POST',
url:"@Html.Action("DisableUser","Admin")",
data: { UserID: userId },
success: function (response) {
// Handle success response if needed
console.log('User deleted successfully');
},
error: function (error) {
// Handle error response if needed
console.error('Error deleting user', error);
}
});
});
#userList
is the id of the jQuery DataTable
.
Here is my action method in my AdminController
:
[HttpPost]
public ActionResult DisableUser(int UserID)
{
if (UserID != 0 && UserID > 0)
{
int result = _helper.DisableUser(UserID);
switch (result)
{
case 1:
TempData["SaveMessage"] = "User disabled successfully";
break;
case -1:
TempData["SaveMessage"] = "Error disabling user";
break;
default:
TempData["SaveMessage"] = "Unknown error";
break;
};
}
var users = RetrieveUserList();
return View("AllUsersData", users);
}
RetrieveUserList()
is fetching the data and will be sent in JSON format. It is bound to my User
model class.
AllUsersData
is the JSON format view for jQuery DataTable
.
When I'm redirected to the view, I get this error:
System.Web.HttpException: 'Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.
on this Line :
url:"@Html.Action("DisableUser", "Admin")",
This is followed by 2 inner exceptions:
HttpException: Execution of the child request failed. Please examine the InnerException for more information
HttpException: A public action method 'DisableUser' was not found on controller 'SiteAdministrator1._1._0.Controllers.AdminController'
What is the main issue I am facing here - any idea ?
It is necessary to use @Url.Action()
instead of @Html.Action()
to generate the correct URL.
When you are using the @Html.Action()
here the MVC Razor engine is trying to find the DisableUser()
action method with the [HttpGet]
attribute and after not finding it throws the HttpException: A public action method 'DisableUser' was not found on controller
.