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

Asked

Viewed 518 times

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 him:

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 database but when it returns to the ajax method it always falls into the error and does not even send the Replay I sent. What can be?

I apologize for taking the parameters this way (mainly the bool thing) and for not using a Bind or anything, but this is not relevant to the question

  • A description of the error found could be useful. Think you can add the console log to the question body?

  • There is no mistake. '. I wish I could help with more details but there is nothing. It simply runs perfectly on C# but when it comes back it just goes right back into the 'error' always, regardless of what I sent from Return in function.

  • In your browser developer’s tool module appears what when the call is made?

  • I’m not really sure, but, you know, this bit of code: JsonRequestBehavior.AllowGet should be JsonRequestBehavior.DenyGet, because the method is decorated with POST, take a test and then leave a message

  • no error appears and the answer is not the one passed by my method but another that has abort length = 1. Help? I took a print but I can’t send it here, right? p

  • Follow the image https://postimg.org/image/e86q3hcol/

  • is not the case to use "Jsonrequestbehavior.Denyget"

  • 1

    The best way to know what is happening is to make a call through Fiddler and see the result, since your call is ok. One remark, I have an application that I use ajax a lot but only with HTTPPOST and I just checked and I don’t use any feedback with Jsonrequestbehavior.AllowGet. Another detail is that I use in all asyncrone calls, following example: public async Task<Jsonresult> Search products(). Since ajax by default is already async.

Show 3 more comments

2 answers

1

This is because you are capturing Exception and giving a Json Re-turn().

When you use Return Json() the http Response is placed with Status Code 20x (success). It’s not because in your json you’re putting Success = true/false that Status Code will change.

To enter the ajax error callback you have to let the Exception burst.

  • actually it always returns me error but what you said I didn’t know. I’ll change it when I get to work tomorrow :D

0

Try returning only Success. At least with Angular and MVC5 always fall into error when passing any result beyond OK.

Another solution is to try to put Response at 200 in hand.

Response.StatusCode = 200

Browser other questions tagged

You are not signed in. Login or sign up in order to post.