Search code examples
ajaxasp.net-corerazor

Why is my Razor controller action call not working when called via Ajax in a Javascript function?


I have an Asp.NetCore Razor application. I am attempting to call into my controller via $ajax() to invoke a contoller action. The action is not getting in my controller. I feel like there is an issue with the way my @Url.Action() in the javascript function is configured. It should be of the form @Url.Action(ActionName, Controller).

I'm not seeing any errors in the devtools window console. What am I doing wrong here?

Here is a C# code snippet containing my DeleteCompany action on the controller:

public class CompanyController : BaseController
{
    [HttpPost]
    public async Task<IActionResult> DeleteCompany(Guid companyId)
    {
        // Do some stuff
        return RedirectToAction("Index");
    }
}

Here is my html snippet where the ConfirmDelete() function gets invoked:

<text>
    <input type="hidden" value="<%- data.CompanyId %>" name="CompanyId" />
    <input type="image" value="<%- data.CompanyId %>" src="/icon/close.png" width="25" height="25" 
           onclick="ConfirmDelete('<%- data.CompanyId %>', '<%- data.CompanyName %>')"/>
</text>

Here is my javascript to prompt for confirmation and make ajax call to controller:

<script>
function ConfirmDelete(companyId, companyName) {
    var message = "<i>Are you sure you want to delete Customer: ".concat(companyName).concat("?");
    var result = DevExpress.ui.dialog.confirm(message, "Confirm Company Delete");
    result.done(function (dialogResult) {
        $.ajax({
          url: '@Url.Action("DeleteCompany","Company")',
          data: { companyId: companyId },
          success: function(data) {
            //call is successfully completed and we got result in data
          },
          error:function (xhr, ajaxOptions, thrownError) {
                          //some errror, some show err msg to user and log the error
                          alert(xhr.responseText);
          }
        });
    });
};
</script>

Solution

  • First you should add type:"Post" in your ajax,then ajax does not support redirection, you should redirect in the success function of Ajax.

    You can change your code like below.

     $.ajax({
          url: '@Url.Action("DeleteCompany","Company")',
          data: { companyId: companyId },
          type:"Post",
          success: function() {
           location.href = '@Url.Action("Index","Company")'
          },
          error:function (xhr, ajaxOptions, thrownError) {
                          //some errror, some show err msg to user and log the error
                          alert(xhr.responseText);
          }
        });
    

    Then in your action:

    [HttpPost]
    public async Task<IActionResult> DeleteCompany(Guid companyId)
    {
        // Do some stuff
         return Ok();
    }