0

I have literally tried everything but can't find a soultion on ajax call back the response always goes to the error attribute of the ajax and no success

jquery-1.9.1.min.js:5 POST http://localhost:60854/ExamController/AjaxMethodForDepartment 500 (Internal Server Error)

Html code:

   <!DOCTYPE html>
<link href="~/Content/css/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/css/bootstrap-multiselect.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/bootstrap-multiselect.js"></script>

<html>
<head>

    <title>CreateExam</title>
</head>
<body>

    <h2>Department</h2>
    <select id="dep" multiple="multiple">

    </select>

    <h2>Batch</h2>
    <select id="batch" multiple="multiple">
        <option disabled selected>-No Department Selected-</option>
    </select>

    <form action="/ExamController/CreateExam" method="post">
        <h2>Subject</h2>
        <select id="subject" multiple="multiple" name="subjects">
            <option disabled selected>-No Batch Selected-</option>
        </select><br><br>
        <input type="submit" />
    </form>
</body>
</html>



$(function () {
$("select").multiselect({
    includeSelectAllOption: true
});


$(document).ready(function () {
    $.ajax({

        type: "POST",
        url: "/ExamController/AjaxMethodForDepartment",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            len = response.length;
            if (len == 0) {
                $("#dep").html('<option disabled selected>-There are no Departments in DB-</option>');
                $("#batch").html('<option disabled selected>-No Department Selected-</option>');
                $("#dep,#batch").multiselect('rebuild');
            }
            else {
                for (var i = 0; i < len; i++) {
                    if (i == 0)
                        $("#dep").html(new Option(response[i].Department_Id, response[i].Department_Id));
                    else
                        $("#dep").append(new Option(response[i].Department_Id, response[i].Department_Id));
                }
                $("#dep").multiselect('rebuild');
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert("error: " + errorThrown);
            $("#dep").html('<option disabled selected>-There are no record of Departments in DB-</option>');
            $("#batch").html('<option disabled selected>-No Department Selected-</option>');
            $("#dep,#batch").multiselect('rebuild');
        }
    });
});

$("#dep").change(function () {
    var len;
    $.ajax({

        type: "POST",
        url: "/ExamController/AjaxMethodForBatch",
        data: JSON.stringify({ departments: $("#dep").val() }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            len = response.length;
            if (len == 0) {
                $("#batch").html('<option disabled selected>-Selected Department does not have any Batch-</option>');
                $("#subject").html('<option disabled selected>-No Batch Selected-</option>');
                $("#batch,#subject").multiselect('rebuild');
            }
            else {
                for (var i = 0; i < len; i++) {
                    if (i == 0)
                        $("#batch").html(new Option(response[i].Batch_Id, response[i].Batch_Id));
                    else
                        $("#batch").append(new Option(response[i].Batch_Id, response[i].Batch_Id));
                }
                $("#batch").multiselect('rebuild');
            }
        },
        error: function (response) {
            alert("Batch Error!");
            $("#batch").html('<option disabled selected>-No Department Selected-</option>');
            $("#subject").html('<option disabled selected>-No Batch Selected-</option>');
            $("#batch,#subject").multiselect('rebuild');                }
    });
});

$("#batch").change(function () {
    var len;
    $.ajax({

        type: "POST",
        url: "/ExamController/AjaxMethodForSubject",
        data: JSON.stringify({ batches: $("#batch").val() }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            len = response.length;
            if (len == 0) {
                $("#subject").html('<option disabled selected>-Selected Batch does not have any Subjects-</option>');
                $("#subject").multiselect('rebuild');
            }
            else {
                for (var i = 0; i < len; i++) {
                    if (i == 0)
                        $("#subject").html(new Option("Subject Id: " + response[i].Subject_Id + ", Subject Name: " + response[i].Subject_Name , response[i].Subject_Id));
                    else
                        $("#subject").append(new Option("Subject Id: " +response[i].Subject_Id + ", Subject Name: " + response[i].Subject_Name , response[i].Subject_Id));
                }
                $("#subject").multiselect('rebuild');
            }
        },
        error: function (response) {
            alert("Subject Error!");
            $("#subject").html('<option disabled selected>-No Batch Selected-</option>');
            $("#subject").multiselect('rebuild');
        }
    });
});

});

Controller:

    public class ExamControllerController : Controller
{
    //
    // GET: /ExamController/

    FYP_DB_Entities obj = new FYP_DB_Entities();

    public ActionResult Index()
    {
        return View();
    }


    public ActionResult CreateExam()
    {
        return View(obj.Departments.ToList());
    }

    [HttpPost]
    public ActionResult ExamCreated(int[] subjects)
    {
        Subject s = new Subject();
        Exam e = new Exam();
        Batch b = new Batch();
        foreach (var i in subjects)
        {
            s = obj.Subjects.First(x => x.Subject_Id == i);
            b = obj.Batches.First(x => x.Batch_Id == s.Batch_Id);

            e.Subject_Id = s.Subject_Id;
            e.Batch_Id = s.Batch_Id;
            e.Department_Id = b.Department_Id;
            e.Total_Marks = 50;
            e.Exam_Session = "Fall-2017";
            e.Status = "Inactive";

            obj.Exams.Add(e);
            obj.SaveChanges();
        }
        return View();
    }

    [HttpPost]
    public JsonResult AjaxMethodForDepartment()
    {
        IEnumerable<Department> departmentList = Enumerable.Empty<Department>();
        try
        {
            departmentList = obj.Departments.ToList();
            return Json(departmentList);
        }
        catch
        {
            return Json(null);
        }
    }

    [HttpPost]
    public JsonResult AjaxMethodForBatch(string[] departments)
    {
        IEnumerable<Batch> batchList = Enumerable.Empty<Batch>();
        try
        {
            batchList = departments.SelectMany(d => obj.Batches.Where(x => x.Department_Id == d));
            return Json(batchList);
        }
        catch
        {
            return Json(null);
        }
    }

    [HttpPost]
    public JsonResult AjaxMethodForSubject(string[] batches)
    {
        IEnumerable<Subject> subjectList = Enumerable.Empty<Subject>();
        try
        {
            subjectList = batches.SelectMany(d => obj.Subjects.Where(x => x.Batch_Id == d));
            return Json(subjectList);
        }
        catch
        {
            return Json(null);
        }
    }

enter image description here

chrome network tab screenshot

enter image description here

faraz
  • 63
  • 11
  • Use your browser tools (the Network tab) to inspect the response which will include details of the error (and what does all that other code have to do with your question?) –  Jul 23 '17 at 07:34
  • because all of the dropdownlists are getting response from ajax call back and all of them are getting this error thats why @StephenMuecke – faraz Jul 23 '17 at 07:38
  • Debug your code :) (and I do not see how the `Index()`, `CreateExam()` and `ExamCreated()` methods are related to your question) –  Jul 23 '17 at 07:39
  • @StephenMuecke i have added network error screenshot i my post would you please take a look? – faraz Jul 23 '17 at 07:44
  • The error means that `Department` contains a property which contains a property that is `Department` (i.e. a circular reference). Return a collection of anonymous objects containing only the properties you need in the view - you only need 2 values - one for the option value and one for the display text. –  Jul 23 '17 at 07:44
  • yes you are right Index(), CreateExam() and ExamCreated() are not related to my question...sorry... my bad ! – faraz Jul 23 '17 at 07:45
  • e.g. `departmentList = obj.Departments.Select(x => new { Value = x.SomeProperty, Text = x.AnotherProperty });` –  Jul 23 '17 at 07:45
  • But the value i want to show in option value and display text is the same value @StephenMuecke – faraz Jul 23 '17 at 07:48
  • Then all you need to return is one value :) - there is no point sending a whole lot of extra data back to the view that you never even use. –  Jul 23 '17 at 07:49
  • Looks like all you want is `obj.Departments.Select(x => x.DepartmentId);` –  Jul 23 '17 at 07:50
  • Then just do it as per the first example I gave you (return an anonymous object containing 2 properties). But there are multiple other issues with you code, including the fact you have no validation at all and that you cannot return the view if anything is invalid (all the data the user selected will be lost). And you should be redirecting once the data is saved, not returning the view. Recommend you study the code (in particular the controller) in [this DotNetFiddle](https://dotnetfiddle.net/1bPZym) –  Jul 23 '17 at 08:11
  • internal server error is gone now...thanks man! you made my day :) @StephenMuecke – faraz Jul 23 '17 at 08:13
  • Yes you are right about validation... I have not applied it yet but now I am going to! @StephenMuecke – faraz Jul 23 '17 at 08:15
  • But I am not getting your point "you cannot return the view if anything is invalid (all the data the user selected will be lost). And you should be redirecting once the data is saved, not returning the view." @StephenMuecke – faraz Jul 23 '17 at 08:18
  • If `ModelState` is invalid, you typically return the view so that error messages are displayed and the user can correct errors. In you case, all the data the user entered will be lost. Study the fiddle (you just need `ListBoxFor()` rather that `DropDownListFor()` where you want a multiple select –  Jul 23 '17 at 08:20
  • yeah you are right :) thanks for notifying the issues now I can work on that and improve the system @StephenMuecke – faraz Jul 23 '17 at 08:25

0 Answers0