skip to Main Content

I know why I am getting this message as the AJAX is completing and expects JSON coming back.

However, I coded the controller action method such that if all is good, redirects to another view. If there is an error is found, return JSON – an error message.

From the AJAX perspective as I am learning, it will expect JSON back regardless of a good (the redirect) or error situation (I return JSON).

So how do I code that up in the AJAX to recognize that no JSON was returned when it is a good situation as I do the redirect and do not programmatically return anything?


The action method executes successfully in the sense that it does the delete, executes the redirect but gets caught on the return and I get the message:

enter image description here


My actions method is:

I have

 Task<ActionResult>

If I try

 Task<JsonResult> 

I get an error on the redirect statement.

    public async Task<ActionResult> DeleteUserProfile()
    {
        string errorMessage = String.Empty;

        try
        {
            Some code to call the web api...

            using (var client = new HttpClient())
            {
                Some code...

                // Call the web api - HTTP POST.
                HttpResponseMessage result = await client.PostAsync(restOfUrl, argsData);

                if (result.IsSuccessStatusCode)
                {
                    return RedirectToAction("Index", "User");
                }
                else
                {
                    // The web api sent an error response.
                    errorMessage = "Server error on deleting the user profile. Reason: " + result.ReasonPhrase;
                }
            }
        }
        catch (Exception ex1)
        {
           Some code...
        }

        // Return a JSON object to show the error message.
        return Json(errorMessage, JsonRequestBehavior.AllowGet);
    }

My view that has the AJAX that calls the method:

    <input class="btn btn-danger deleteButton" value="Delete Your Profile">

There is a Modal window and on a Yes, executes the AJAX. And I was thinking it would only come back if I pushed the JSON with the error message.

        $('.btn-yes11').click(function() {
            $('#myModal11').modal('hide');

            $.ajax({
                type: 'POST',
                url: '@Url.Action("DeleteUserProfile", "UserProfile")',
                dataType: "json",
                success: function(jsondata) {
                    if (jsondata.length > 0)
                    {
                        // Set the error message.
                        $("#jsonErrorMessage").text(jsondata);
                        // Show.
                        $("#jsonErrorMessage").css("display", "block");
                    }
                    else
                    {
                        // Hide.
                        $("#jsonErrorMessage").css("display", "none");
                    }
                 },
                error: function(xhr, ajaxOptions, thrownError) {
                    alert('Critical Error: something is wrong in the call to DeleteUserProfile for delete! Status: ' + xhr.status + '. Error: ' + thrownError.toString() + '. Response Text: ' + xhr.responseText);
                }
            });

            return true;
        }); 

2

Answers


  1. Chosen as BEST ANSWER

    My code for resolving my issue (it no longer does a redirect and always sends back a JSON object):

     public async Task<JsonResult> DeleteUserProfile()
     {
        string errorMessage = String.Empty;
        bool RedirectSwitch = false;
    
        try
        {
            Some code to call the web api...
    
            using (var client = new HttpClient())
            {
                Some code...
    
                // Call the web api - HTTP POST.
                HttpResponseMessage result = await client.PostAsync(restOfUrl, argsData);
    
                if (result.IsSuccessStatusCode)
                {
                   // Set the switch so that the AJAX call will go to the User controller.
                   RedirectSwitch = true;
                }
                else
                {
                    // The web api sent an error response.
                    errorMessage = "Server error on deleting the user profile. Reason: " + result.ReasonPhrase;
                }
            }
        }
        catch (Exception ex1)
        {
           Some code...
        }
    
        if (errorMessage != "")
        {
          // Set an error code which will initiate the AJAX function: 'error: function (error) {}'.
          Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        }
    
        // Creates JSON representation of anonymous data.
        // Return a JSON object.
        return Json(new { Redirect = RedirectSwitch, ErrorMessage = errorMessage });
    }
    

    The Ajax:

      $.ajax({
                type: 'POST',
                url: '@Url.Action("DeleteUserProfile", "UserProfile")',
                dataType: "json",
                success: function (result) {
                    if (result.Redirect)
                    {
                        // A successful delete - so go to the User controller. To the index action which returns the ViewsUserUser.cshtml.
                        window.location.href = "/User/Index/";
                    }
                 },
                error: function (error) {
                   // Set the error message from the key/value pair set in the controller: ErrorMessage = errorMessage.
                    $("#jsonErrorMessage").text(error.responseJSON.ErrorMessage);
                    // Show it.
                    $("#jsonErrorMessage").css("display", "block");
                }
     });
    

  2. try this way may be useful.

    Controller

    public JsonResult Create(MyObject myObject) 
    {
      //AllFine
      return Json(new { IsCreated = True, Content = ViewGenerator(myObject));
    
      //Use input may be wrong but nothing crashed
      return Json(new { IsCreated = False, Content = ViewGenerator(myObject));  
    
      //Error
      Response.StatusCode = (int)HttpStatusCode.InternalServerError;
      return Json(new { IsCreated = false, ErrorMessage = 'My error message');
    }
    

    JS

    $.ajax({
         type: "POST",
         dataType: "json",
         url: "MyController/Create",
         data: JSON.stringify(myObject),
         success: function (result) {
           if(result.IsCreated)
         {
        //... ALL FINE
         }
         else
         {
        //... Use input may be wrong but nothing crashed
         }
       },
        error: function (error) {
                alert("Error:" + erro.responseJSON.ErrorMessage ); //Error
            }
      });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search