abalter abalter - 1 month ago 11
Javascript Question

Ajax call not reaching controller method

Yes, there are a whole bunch of posts with similar questions. I've tried to follow the answers in them, but my ajax call still isn't reaching the controller method.

controller (SalesController.cs):

[HttpGet]
public JsonResult fillVarietiesSelect(int species_id)
{
String[] alist = {"a","b","c"};
return Json(alist, JsonRequestBehavior.AllowGet);
}


javascript:

$('#species-select').on('change', function () {
var species_id = $('#species-select').val();
console.log("species id selected " + species_id);
alert("species id selected " + species_id);
$('#variety-select').empty();
$.ajax({
type: 'GET',
url: '@Url.Action("fillVarietiesSelect", "Sales")',
data: {species_id : species_id},
success: function (result) {
alert(result);
}
});
});


The on change event is firing, and the alert pops up with the correct data. I have a breakpoint set at the controller method, but execution doesn't seem to get there.

Answer

try doing exactly like following

Controller:

    [HttpGet]
    public ActionResult receive2(string p)
    {
        ViewBag.name = p;
        List<string> lst = new List<string>() { p };
        return Json(lst,JsonRequestBehavior.AllowGet);

    }

Client side

      $.ajax({
            type: "GET",
            url: "Main/receive2", // the method we are calling
            contentType: "application/json; charset=utf-8",
            data: { "p": $("#txtname").val() },
             dataType:"json",
            success: function (result) {
                alert("yes");
                alert('Yay! It worked!tim' + result);
                window.location = "http://google.com";
                // Or if you are returning something

            },
            error: function (result) {
                alert('Oh no aa :(' + result[0]);
            }

        });

I have checked it's working