简体   繁体   中英

Ajax request for asp.net mvc controller returning 500 - internal server error

I have these two select s on a view:

<select class="input-sm form-control input-s-sm inline" onchange="carregarCidades()" id="comboEstado">
    ...
</select>

<select class="input-sm form-control input-s-sm inline" id="comboCidade">
   ...
</select>

The first represents a State, and when I select it I want to execute the carregarCidades function to load the cities of that stat and them load them in the other select. Here is the function:

function carregarCidades() {
    var url = "@Url.Action("CarregarCidades", "Usuario")";

    var estado = $("#comboEstado").find(":selected").text();

    $.get(url, { pEstado: estado }, function (cidades) {
        $("#comboCidade").html(""); // clear before appending new list 
        $.each(cidade, function (i, cidade) {
            $("#comboCidade").append(
                $('<option></option>').val(cidade.id_cidade).html(cidade.cidade));
        });
    });
}

Now, here is the CarregarCidades action in the UsuarioController:

public ActionResult CarregarCidades(string pEstado)
{
    string cCidades = oVFP.BuscaCidade(pEstado);

    DataSet dsC = new DataSet();
    dsC.ReadXml(new StringReader(cCidades));

    JsonResult result = Json(dsC.Tables["curretorno"]);
    return result;
}

I'm debugging the action and apparently everything is ok:

在此输入图像描述 在此输入图像描述

But, after the Action returns the Json result, the callback funcion is not called on the jquery code and I got a 500 internal server error in my console.

You have to JsonAllowRequestbehavior parameter to AllowGet , by default it is DenyGet :

JsonResult result = Json(dsC.Tables["curretorno"],JsonRequestBehavior.AllowGet);

You can read about Why it is needed on this post .

I would first make sure your method has the [WebMethod] attribute above its declaration.

The second thing I would suggest is returning your Json like this:

return Json(result, JsonRequestBehavior.AllowGet);

Generally it is one of or both of these issues that gives you a 500 error.

Edit:

Declaring it as a [WebMethod] may not be necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM