Domanda

Nel mio progetto ASP.NET MVC3, utilizzo una chiamata AJAX per inviare i dati JSON a Crea ActionMethod nella società controller. Ma quando eseguo il debug della chiamata Ajax, finisce sempre in un risultato di errore invece del risultato dei successi.

Ajax Call:

$.ajax({
            url: '/Company/Create',
            type: 'POST',
            data: JSON.stringify(CreateCompany),
            dataType: 'Json',
            contentType: 'application/json; charset=utf-8',
            success: function () {
                alert('ajax call successful');
            },
            error: function () {
                alert('ajax call not successful');
            }
        });

Il mio metodo di azione nel controller dell'azienda:

    [HttpPost]
    public ActionResult Create (Company company)
    {
        try
        {
            //Create company
            CompanyRepo.Create(company);
            return null;
        }
        catch
        {
            return View("Error");
        }
    }

Ho già eseguito il debug di ActionMethod, ma lo completa come dovrebbe. Quindi i dati inviati con la chiamata AJAX verranno gestiti e scritti al DB. (Il metodo di azione non utilizza la parte di cattura).

Perché la mia chiamata Ajax dà ancora al messaggio "Ajax Call non di successo"?

È stato utile?

Soluzione

Avevo lo stesso problema con il risultato del risultato JSON. Quello che ho fatto è impostare il tipo di dati su "testo json" :)) se questo non aiuta a ottenere informazioni aggiuntive acquisendo i dettagli del tuo errore, cioè:

$.ajax({
        url: '/Company/Create',
        type: 'POST',
        data: JSON.stringify(CreateCompany),
        dataType: 'text json',
        contentType: 'application/json; charset=utf-8',
        success: function () {
            alert('ajax call successful');
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("XMLHttpRequest=" + XMLHttpRequest.responseText + "\ntextStatus=" + textStatus + "\nerrorThrown=" + errorThrown);
        }
    });

BTW: ho trovato questa soluzione da qualche parte su StackOverflow

Altri suggerimenti

Perché stai tornando null In caso di successo nella tua azione controller? Restituisci qualcosa al successo come ad esempio un oggetto JSON (specialmente come indicato nella tua richiesta AJAX che ti aspetti la risposta JSON dal server, usando il dataType: 'json' impostazione - che dovrebbe essere minuscola j a proposito):

return Json(new { success = true });

Non sarebbe solo più facile:

$.post("/Company/Create", function (d) {
    if (d.Success) {
        alert("Yay!");
    } else {
        alert("Aww...");
    }
}, "json");

E nel tuo controller.

[HttpPost]
public JsonResult Create(
    [Bind(...)] Company Company) { <- Should be binding
    if (this.ModelState.IsValid) { <- Should be checking the model state if its valid
        CompanyRepo.Create(Company);

        return this.Json(new {
            Success = true
        });
    };

    return this.Json(new {
        Success = false
    });
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top