Home > Software engineering >  ASP.NET MVC: After Delete Action, Index is not rendering
ASP.NET MVC: After Delete Action, Index is not rendering

Time:12-02

I have a controller which has Add, Edit, Delete and Index action methods. For my Add action, after the add, it redirects to Index in order to refresh the grid to show the add.

For Delete it is not redirecting. The delete is occurring, but I only see it if I manually refresh the page. I tried

return RedirectToAction(nameof(Index));  

and

w("Index", otList); 

where "otList" is the model.

The is the code that invokes the delete action in the controller

    $("#deleteButton").click(function () {
            var button = $(this);
            $.ajax({ method: 'POST', url: button.data('url') })
                .done(function () {
                    $('#confirmModal').modal('hide');
                    button.removeData('url');
                })
                .fail(function () {
                    magalert.communicationError();
                });
        });

Here is the Delete action method in the controller

    public IActionResult Delete(int Id)
    {
        try
        {
            var jurisdictionId = _user.Current().JurisdictionId;
            _electedOfficials.deleteOrgType(jurisdictionId, Id);

            //Refresh data post delete for the grid
            List<OrganizationType> otList = new List<OrganizationType>();
            otList = (List<OrganizationType>)_electedOfficials.OrgTypeList(jurisdictionId);

            //return View(otList);

            //return RedirectToAction(nameof(Index));

            return View("Index", otList);
        }
        catch (Exception e)
        {
            _logger?.LogCritical(new EventId(103, "CAdminOrganizationType"), e, $"Error when deleting id: "   Id);
            throw;
        }
    }

Any ideas why the Index view is not refreshing like it does for after the Add action? I tried to redirect and tried specifying the view and model in the return.

Here is the Index action method if that helps

    public IActionResult Index()
    {
        try
        {
            var jurisdictionId = _user.Current().JurisdictionId;
            List<OrganizationType> otList = new List<OrganizationType>();
            otList = (List<OrganizationType>)_electedOfficials.OrgTypeList(jurisdictionId);
            return View(otList);
        }
        catch (Exception e)
        {
            _logger?.LogCritical(new EventId(101, "CAdminOrganizationType"), e, $"Error when loading Organization Types View");
            throw;
        }
    }

CodePudding user response:

If you are invoking the delete with Ajax you can't perform a redirection, one way to solve this is to refresh the page from the javascript code using location.reload(); When the request is successful after button.RemoveData('url'); Of course, if the delete is performed from the index page.

  • Related