Pow4Pow5
Pow4Pow5

Reputation: 501

ASP.NET MVC Ajax function keep failing?

I would like to know why the function called by AJAX keeps fail in this scenario? The FillObj() is supposed to be called when a dropdownlist selection changes.

    <div class="form-group">
        @Html.LabelFor(model => model.Module, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.Module, new SelectList(Model.ModuleList, "Value", "Text"),
     "- Please select a Module -", new { @onchange = "FillObj()", @class = "form-control" })
        </div>
    </div> 

As you can see I already have the @onchange set to FillObj() in the Dropdownlist code. However, when the selection changes, it keep goes to alert('A error') instead of success. The following is the AJAX function:

function FillObj() {
    var moduleID = $('#Module').val();
    $.ajax({
        url: '/Questions/FillObjectives',
        type: "GET",
        dataType: "JSON",
        data: { module: moduleID },
        success: function (objectives) {
            $("#objective").html(""); // clear before appending new list
            $.each(objectives, function (i, Obj) {
                $("#objective").append(
                    $('<option></option>').val(Obj.ObjectiveId).html(Obj.objective));
            });
        },
        error: function () {
            alert('A error');
        }

    });
}

Controller:

public ActionResult FillObjectives(int module)
{
    var objectives = db.Objectives.Where(o => o.ModuleId == module);
    return Json(objectives, JsonRequestBehavior.AllowGet);
}

EDIT 1:

Ok, I did some debugging and found out that this error message occured whenever the function is called:

enter image description here

Anyways to fix this?

Upvotes: 2

Views: 103

Answers (1)

CodingYoshi
CodingYoshi

Reputation: 27009

Please see edit below in EDIT 1

If you are calling your action using GET, then you cannot send data in the body. You cannot do this:

data: { module: moduleID },

You can append it to the end of the url as a querystring.

url: '/Questions/FillObjectives?module=' + moduleID,

Or you can change the call to POST but make sure your action does not have HttpGet attribute applied to it.

EDIT 1

Thanks to the comments by Stephen Muecke, above I said that for a GET operation data { module: moduleID } should not be done. That is half true. And since this answer was upvoted a few times, I am sharing this so other people, who are under the same impression, will know that is is not true. It will not work if whatever being posted is already a string. If it is not a string, jQuery will convert it to a string and append it to the URL. This is from jQuery docs:

Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests.

In the question posted, it is not already a string so jQuery will convert the data to a string and append it to the url.

Therefore, in conclusion, the code posted in this question will work but the reason it is going to error is because the code in the controller is erroring out. If you do this in the controller, it will go to success on the client side:

public ActionResult FillObjectives(int module)
{
     var data = new[]{ new { ObjectiveId = 1, objective = "Option 1" }, new { ObjectiveId = 2, objective = "Option 2" } };
     return Json(data, JsonRequestBehavior.AllowGet);
}

So the issue most likely is with this line of code:

var objectives = db.Objectives.Where(o => o.ModuleId == module);

Upvotes: 1

Related Questions