1

I'm new in JQuery and AJAX. I tried to fill a DropDownList using AJAX in ASP.NET MVC 4 and it gives me this error: The ObjectContext instance has been deleted and can not be used for operations that require a connection. and here is my script:

function LoadFlights() {
var $flight = $('#IDFLIGHT');
$flight.empty();
$flight.append($('<option></option>').val('').html('Please Wait...'));

$.ajax({
    url: '/Flight/GetFlightList',
    type: 'POST',
    data: {},
    dataType: 'json',
    success: function (d) {
        $flight.empty();
        $flight.append($('<option></option>').val('').html('Select Flight'));
        $.each(d, function (i, val) {
            $flight.append($('<option></option>').val(val.IDFLIGHT).html(val.DATEFLIGHT));
        });
    },
    error: function () {

    }
});
}

And this is the action in the controller Flight I call:

public JsonResult GetFlightList()
    {
        FlightService flightService = new FlightService();
        var all = flightService.GetAll();
        return new JsonResult { Data = all, JsonRequestBehavior = JsonRequestBehavior.AllowGet };         
    }

The variable all has data but it still give me the error mentioned above. Thank you

5
  • 1
    So you are saying that ajax call comes to server to your action and return successfully from action? Commented Dec 14, 2015 at 15:18
  • No, didn't say that it return successfully from the action. But I said that the variable "all" has the value. the problem is in returning data as JSON I guess Commented Dec 14, 2015 at 15:33
  • replace $.each(d with $.each(d.Data Commented Dec 14, 2015 at 19:15
  • it still give the same error ! Commented Dec 14, 2015 at 19:33
  • Materialize your query - var all = flightService.GetAll().ToList(); If that is not working, show your GetAll() method. Commented Dec 14, 2015 at 21:23

1 Answer 1

1

You should use return Json(all,JsonRequestBehavior.AllowGet);, just passing the list data to the constructor will not convert it to JSON object.

P.S. the funtion Json() will return JsonResult

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

Comments

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.