1

I have 2 dropdownlist on a page.When i select some value from first dropdown list then in second dropdownlist all the values should load according to the value selected (Subcategories loaded according to Categories). Here is what I tried but it doesn't work:

Model

 public class Product
    { ...
      public int CategoryId { get; set; }
      public virtual Category Category { get; set; }
      public IEnumerable<SelectListItem> Categories { get; set; }

      public int SubCategoryId { get; set; }
      public virtual SubCategory SubCategory { get; set; }
      public IEnumerable<SelectListItem> SubCategories { get; set; }
      ...
    }

View

  <label>Select Category</label>
  @Html.DropDownListFor(m => m.CategoryId, new SelectList(Model.Categories, "Value", "Text"), "Select Category", new { id = "catList", @class = "form-control" })

  <label>Selectat Subcategory</label>
  @Html.DropDownListFor(m => m.SubCategoryId, new SelectList(Enumerable.Empty<SelectListItem>(), "Value", "Text"), "Selectat Subcategory", new { id = "subcatList", @class = "form-control" })
<script type="text/javascript">
    $(document).ready(function () {
        $("#catList").change(function () {
            var cID = $(this).val();
            $.getJSON("../Product/New/LoadSubCategories", { catId: cID },
                function (data) {
                    var select = $("#subcatList");
                    select.empty();
                    select.append($('<option/>', {
                        value: 0,
                        text: "Selecteaza o subcategorie"
                    }));
                    $.each(data, function (index, itemData) {
                        select.append($('<option/>', {
                            value: itemData.Value,
                            text: itemData.Text
                        }));
                    });
                });
        });
    });
</script>

Controller

[AcceptVerbs(HttpVerbs.Get)]
public JsonResult LoadSubCategories(string catId)
{
    var subCatList = GetAllSubCategories(Convert.ToInt32(catId));
    return Json(subCatList, JsonRequestBehavior.AllowGet);
}

[NonAction]
public IEnumerable<SelectListItem> GetAllSubCategories(int selectedCatId)
{
      //generate empty list
      var selectList = new List<SelectListItem>();

      var subcategories = from sbcat in db.SubCategories
                          where sbcat.CategoryId == selectedCatId
                          select sbcat;
      foreach (var subcategory in subcategories)
      {
           //add elements in dropdown
           selectList.Add(new SelectListItem
           {
                Value = subcategory.SubCategoryId.ToString(),
                Text = subcategory.SubCategoryName.ToString()
            });
       }
      return selectList;
}
AlexandraP
  • 27
  • 1
  • 6
  • So what is happening with your current code ? Are you seeing any script errors ? Is your network call successful ? – Shyju Dec 13 '18 at 22:17

2 Answers2

0

you need to change your getJson to Ajax method

here is the ajax sample code

$.ajax({
                type: "GET",
                url: '/Product/New/LoadSubCategories',
                data: {catId: cID},
                success: successFunc,
                error: errorFunc
            });

            function successFunc(data) {     
                var select = $("#subcatList");
                select.empty();
                select.append($('<option/>', {
                    value: 0,
                    text: "Selecteaza o subcategorie"
                }));
                $.each(data, function (index, itemData) {
                    select.append($('<option/>', {
                        value: itemData.Value,
                        text: itemData.Text
                    }));
                });
            }

            function errorFunc() {
                alert('error');
            }
        });

this ajax code you need to write on dropdown change and in success of ajax call, you need to write the code you want to do when dropdown's value changes and data received successfully

Yash Soni
  • 764
  • 3
  • 14
0

For change the second Drop down value according to first drop down value, you need to write an Onchange event, then only it will get change.. please check below stackoverflow question an answer it will be help full to you

Click here

Shakir Ahamed
  • 1,290
  • 3
  • 16
  • 39