Search code examples
javascriptc#jqueryasp.net-mvcasp.net-ajax

Why is my Jquery Ajax call not working?(Asp.net MVC C#)


My aim was to use ajax to retrieve some data from my controller and append this to a table element in my view. However the javascript code only works until "$.ajax(" at which point it just stops. I placed some break points after the above mentioned point but the code never "broke" at those points.

This is the javascript code

$(document).ready(function ()
{
    $("#DivisionId").change(function () {
        var OptionId = $('#DivisionId').val();
        var position = 0;
        $.ajax(
            {
                type: 'POST',
                url: '@URL.Action("Division")',
                dataType: 'json',
                data: { DivisionId: OptionId },
                success: function (data) {
                    var LogStandings = '';
                    $.each(data, function (i, log) {
                        position++;
                        var Logs = "<tr>" +
                            "<td>" + position + "</td>" +
                            "<td>" + log.Logs1.Team.TeamName + "</td>" +
                            "<td>" + log.Logs1.Played + "</td>" +
                            "<td>" + log.Logs1.Win + "</td>" +
                            "<td>" + log.Logs1.Draw + "</td>" +
                            "<td>" + log.Logs1.Lost + "</td>" +
                            "<td>" + log.Logs1.GoalsFor + "</td>" +
                            "<td>" + log.Logs1.GoalsAgainst + "</td>" +
                            "<td>" + log.Logs1.GoalDifference + "</td>" +
                            "<td>" + log.Logs1.Points + "</td>" +
                            "</tr>";
                        $('#TheLog').append(Logs);
                    });

                },
                error: function (ex) {
                    var r = jQuery.parseJSON(response.responseText);
                    alert("Message: " + r.Message);
                    alert("StackTrace: " + r.StackTrace);
                    alert("ExceptionType: " + r.ExceptionType);
                }
            });
        return false;

    }); // end of Division on change function

})//End of document.ready function

This is the code in my controller

        public JsonResult Division(int DivisionId)
        {
            int UnderId = db.Under.FirstOrDefault().UnderID;
            MainDivisionId = id;


            List<FixtureModel> Fixtures = db.Fixtures.Where(f => f.TeamModel.DivisionId == id && f.TeamModel.UnderId == UnderId).ToList();
            List<ResultModel> Results = db.Results.Where(r => r.Fixtures.TeamModel.DivisionId == id && r.Fixtures.TeamModel.UnderId == UnderId).ToList();
            List<LogModel> Logs = db.Logs.Where(l => l.Team.DivisionId == id && l.Team.UnderId == UnderId).ToList();

            IndexViewModel IndexPage = new IndexViewModel(Fixtures, Results, Logs);

            return Json(IndexPage , JsonRequestBehavior.AllowGet);
        }

I searched a little on the internet and one source suggested that I place my jquery CDN at the top of my view within the head tag, this did not solve my problem though. Besides that I have not been able to find any other solutions after an hour of searching.


Solution

  • You have 2 issues that I can see.

    First, you're making a POST request to a controller action that does not have the [HttpPost] annotation. It seems to me that you're getting/selecting data and a GET request would be more appropriate so I've used that in the example below.

    Second, you cannot use @URL.Action("Division") in a javascript string (or in javascript in general. If you really needed to then you could store some data in a hidden div and get the value with javascript/jquery) like you're attempting to do. On the script itself, this will render as you're making a request directly to localhost:12345/@URL.Action("Division") which is not a valid path. See the example below:

    Script:

    $(document).ready(function () {
        $("#testButton").on("click", function () {
            var OptionId = 1;
    
            $.ajax(
                {
                    type: 'GET',
                    //this url assumes your controller action is in HomeController.cs
                    url: '/Home/Division/' + OptionId,
                    dataType: 'json',
                    data: { DivisionId: OptionId },
                    success: function (data) {
                        alert("success");
    
                    },
                    error: function (ex) {
                        var r = jQuery.parseJSON(response.responseText);
                        alert("Message: " + r.Message);
                        alert("StackTrace: " + r.StackTrace);
                        alert("ExceptionType: " + r.ExceptionType);
                    }
                });
        });
    });
    

    HomeController.cs action:

    public JsonResult Division(int DivisionId)
    {
        return Json(1, JsonRequestBehavior.AllowGet);
    }
    

    and in my view for testing:

    <button type="button" id="testButton" class="btn btn-primary btn-lg">TEST BUTTON</button>

    The above test works as expected (receives the DivisionID param, returns data from the controller action and alerts success to the client). With the changed outlined above, breakpoints in your controller action will be hit as you're specifying a valid path and making the appropriate request type. Hope this helps.