Ajax always falls into 'error' even when successful (C # MVC5)

0

Come on. I have the following method:

C #

    [HttpPost]
    [AllowAnonymous]
    public JsonResult PostOnCRM(string textBoxFirstName, string textBoxCountry, string textBoxLastName, string textBoxEmail, string textBoxTitle, string textBoxTelephone, string textBoxCompany, string textBoxWebsite, string textAreaNote, string checkBoxUpdates)
    {
        try
        {
            bool isValidEmail = Regex.IsMatch(textBoxEmail,
            @"^(?("")("".+?(?<!\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^'\{\}\|~\w])*)(?<=[0-9a-z])@))" +
            @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
            RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));

            if (!isValidEmail)
                throw new Exception("E-mail is not a valid one");
            LeadInformation lead = new LeadInformation()
            {
                Subject = "Web site",
                FirstName = textBoxFirstName,
                LastName = textBoxLastName,
                JobTitle = textBoxTitle,
                Address1_Country = textBoxCountry,
                EmailAddress1 = textBoxEmail,
                MobilePhone = textBoxTelephone,
                WebsiteUrl = textBoxWebsite,
                Description = textAreaNote,
                DoNotEmail = checkBoxUpdates.Contains("Yes") ? true : false
            };
 //Aqui existe um método de insert que funciona corretamente

            return Json(new { success = true, responseText = "Your message successfuly sent!" }, JsonRequestBehavior.AllowGet);
        }
        catch (Exception e)
        {
            return Json(new { success = false, responseText = e.Message }, JsonRequestBehavior.AllowGet);
        }
    }

And I make an ajax call to it:

Ajax

$("#formContact").submit(function (evt) {
    evt.preventDefault();

    var formdata = $('form').serialize();
    $.ajax({
        type: 'POST',
        dataType: "json",
        cache: false,
        url: 'http://localhost:59289/Lead/PostOnCRM',
        data: formdata,
        success: function (response) {
            alert(response);
        },
        error: function (response) {
            alert('Error - ' + response.responseText);
        }
    });
});

The method performs perfectly. It does the insert in the bank but when it returns to the ajax method it always falls in the 'error' and does not send nor the response that I sent. What can it be?

I already apologize for picking up the parameters in this way (especially the bool bid) and for not using a Bind or anything, but this is not relevant to the question

    
asked by anonymous 12.10.2016 / 19:23

2 answers

1

This happens because you are capturing the exception and giving a Json () return.

When you use the return Json () the http response is placed with Status Code 20x (success). It is not because in your json you are putting success = true / false that the Status Code will change.

To enter the ajax error callback you have to let the exception pop up.

    
12.10.2016 / 23:23
0

Try to return only success. At least Angular and MVC5 always fall into error when passing any result other than OK.

Another solution is to try for the Response in 200 at hand.

Response.StatusCode = 200
    
13.10.2016 / 02:51