1

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.

7
  • The request reaches your controller? Commented Jan 29, 2020 at 17:47
  • It does not. The execution of the JavaScript code does not pass the "$.Ajax" part Commented Jan 29, 2020 at 17:52
  • Your ajax call specifies POST...do you have the [HttpPost] attribute on your controller method? Also, where exactly were the breakpoints you set? Were they for example on the return false? Or in the success or error callbacks? Commented Jan 29, 2020 at 17:53
  • try to add JSON.stringify to your Data Commented Jan 29, 2020 at 17:57
  • @David784 I do not have the [HttpPost] attribute. Let me try that now. And the break points were 1. Just above the ajax part, the code broke at that point. 2. by LogStandings variable, the code did not break at this point. Commented Jan 29, 2020 at 17:57

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I am a little confused. It seems like in your explanation you say that I should change my url value by the ajax section, but you have not changed yours in the example code. Am mistaken?
I have followed your example here but I am still facing the same problem. I placed a breakpoint just above the $.Ajax part and the moment i click on continue in my IDE, the program crashes and Chrome says "Oh snap, something went wrong while trying to view the webpage".
and do you get any console errors or exceptions thrown in your controller? I'm not sure what else to do here as I created a blank MVC solution and the most simple possible test case which recreated your issue then made the adjustments to make it operational (and tested successfully). Try removing the breakpoints from your client side and just put one at the beginning of the controller action and see if it gets hit (it should if youve made the suggested changes)
You can also utilize the network tab in the chrome debugger to verify the request is being made, verify what path the request is being made to and verify the data that is being sent (tools like Fiddler are also very helpful in testing these calls)
Making use of the network tab in the chrome debugger was very helpful. It seems like the URL Ajaz is using is localhost:1171/Website/Division?DivisionId=2 , which is why we are getting our problem.
0

I also had same problem like that. I did that in a script tag placed inside head tag. But I had to place that inside body tag. Then it worked fine. Try to use. It might help.

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.