javascriptc#htmlmodel-view-controllerjsonresult

Fix URL to return dropdownlist items with JsonResult - MVC- C#


My js dropdown code:

       $(document).ready(function () {
    $("#ddDivision").change(function () {
        $.get("GetDepartment", { id: $("#ddDivision").val() }, function (data) {
              $("#ddDept").empty();
              $("#ddDept").append("<option value='Please Select'>Please Select</option>")
              $.each(data, function (index, row) {
                  console.log(row);
                  $("#ddDept").append("<option value='" + row.Value + "'>" + row.Text + "</option>")
              });
          });
      })
  });

The JsonResult that returns the list:

      public JsonResult GetDepartment(int id)
    {
        List<SelectListItem> items = new List<SelectListItem>();
        //query to return items
        return Json(items, JsonRequestBehavior.AllowGet);
    }  

The error I get (the dropdown does not populate) but I get this in F12 dev tools:

http://localhost/Home/EditView/GetDepartment?id=2

So the URL is wrong, because its on EditView, it should return GetDepartment list, but it doesnt. How do I fix the URL ?

When I'm on the Index view, it returns the correct URL like Home/GetDepartment - how to fix this when using another view?

Also to mention, I use one controller, HomeController.


Solution

  • There are two ways to fix this problem of urls.

    Way 1:

    Normally the recommended approach is to use the Url.Action helper method which makes sure to generate the correct url for the specified controller and action like:

    $.get('@Url.Action("GetDepartment","Home")', { id: $("#ddDivision").val() }, function (data)
    

    Way 2:

    and if the js code is in a separate js file then what we do is use data attributes of html elements like:

    <select id="ddlDivision" data-url='@Url.Action("GetDepartment","Home")'>
    

    and then in js what we can do is to use that url from data- attributes like below:

     $("#ddDivision").change(function () {
        var url = $(this).data("url");
        $.get(url , { id: $("#ddDivision").val() }, function (data) {
    

    Hope it gives you idea of either way.