0

I work with ASP.NET MVC and I have an ODBC connection for database and have retrieved two drop down list from controller to view using queries.

Those two drop down lists are:

 @Html.DropDownListFor(model => model.storageLocation, new SelectList(Model.locationGroupDD, "storageLocation", "storageLocation"), "Choose Location Group", new { @id = "storageLocation", @class = "dropdown1" })

@Html.DropDownListFor(model => model.storageLocationList, new SelectList(Model.locationDD,"storageLocationList","storageLocationList"), "Choose Location", new { @id = "storageLocationListDropDown", @class = "dropdown1" })

I'm new to JQuery and not sure how to script this. However, I found this script online and tried using the following to make necessary changes but I literally don't know how to modify/proceed. Any help is appreciated! Thank you.

Following are the queries I used to retrieve the data from database:

 For drop downlist 1: select abc from xyz;
For drop downlist 2: select pqr from lmn where abc = "some value";

I want to pass the selected value from drop down list 1 to controller to execute query for second drop down list.

  • I suggest you read how to use AJAX for cascading `DropDownListFor`/DDLF [here](https://stackoverflow.com/questions/25794651/cascading-dropdownlistfor-asp-net-mvc) and [here](https://stackoverflow.com/questions/5497524/easiest-way-to-create-a-cascade-dropdown-in-asp-net-mvc-3-with-c-sharp). Basically you need to handle `change` event on first DDLF, then use `jQuery.ajax()` and put query results to second DDLF. – Tetsuya Yamamoto Aug 31 '18 at 21:31
  • Refer [this DotNetFiddle](https://dotnetfiddle.net/1bPZym) for a working example –  Aug 31 '18 at 21:46

1 Answers1

0

Please follow the following steps to make Cascading DropdownList in ASP.NET MVC:

1. In your Controller:

public class YourControlleNameController : Controller
{
   public ActionResult Create()
   {
        var LocationGroupDDList = _dbContext.LocationGroupDD.Select(lgdd => 
                                             new { lgdd.LocationGroupDDId, lgdd.LocationGroupDDName }).ToList();

        ViewBag.LocationGroupDDSelectList = new SelectList(LocationGroupDDList, "LocationGroupDDId", "LocationGroupDDName");

        ViewBag.LocationDDListSelectList = new SelectList(new List<LocationDD>(), "LocationDDId", "LocationDDName");

        return View();
   }

  [HttpPost]
  public ActionResult Create(YourModel model, string LocationGroupDDId)
  {
        if (ModelState.IsValid)
        {
            // Do necessary staff here
        }
        var LocationGroupDDList = _dbContext.LocationGroupDD.Select(lgdd => 
                                             new { lgdd.LocationGroupDDId, lgdd.LocationGroupDDName }).ToList();

        ViewBag.LocationGroupDDSelectList = new SelectList(LocationGroupDDList, "LocationGroupDDId", "LocationGroupDDName",LocationGroupDDId);

        var LocationDDList = _dbContext.LocationDD.Where(ldd => ldd.LocationGroupDDId == LocationGroupDDId).Select(ldd => new {ldd.LocationDDId, ldd.LocationDDName}).ToList();

        ViewBag.LocationDDListSelectList = new SelectList(LocationDDList, "LocationDDId", "LocationDDName",model.LocationDDId);

        return View();
  }



   public JsonResult GetLocationDDByLocationGroupDD(string LocationGroupDDId)
   {
        var LocationDDList = _dbContext.LocationDD.Where(ldd => ldd.LocationGroupDDId == LocationGroupDDId)
                                                  .Select(ldd => new {ldd.LocationDDId, ldd.LocationDDName}).ToList();

        return Json(LocationDDList, JsonRequestBehavior.AllowGet);
   }

}

2. In the View:

<div class="form-group">
    @Html.Label("LocationGroupDD", "Location GroupDD Name", htmlAttributes: new { @class = "control-label" })
    @Html.DropDownList("LocationGroupDDId", ViewBag.LocationGroupDDSelectList as SelectList, "Select Location GroupDD", htmlAttributes: new { @class = "form-control",  @id = "LocationGroupDD" })

</div>
<div class="form-group">
    @Html.Label("LocationDD", "LocationDD Name", htmlAttributes: new { @class = "control-label" })
    @Html.DropDownList("LocationDDId", ViewBag.LocationDDListSelectList as SelectList, "Select LocationDD", htmlAttributes: new { @class = "form-control", @disabled = "disabled", @id = "LocationDD" })                   
</div>

3. jQuery in the view:

@section Scripts {
    <script type="text/javascript">
      $(document).on('change','#LocationGroupDD', function(){
          var LocationGroupDDId = $(this).val();
          $('#LocationDD').empty();
          if (LocationGroupDDId) {
            $.ajax({
                type: "GET",
                url: '@Url.Action("GetLocationDDByLocationGroupDD", "YourControlleName")',
                data: { LocationGroupDDId: LocationGroupDDId},
                success: function(data) {
                    if (data.length > 0) {
                        $('#LocationDD').prop("disabled", false);
                        $('#LocationDD').append($("<option>").val("").text("Select LocationDD"));
                        $(data).each(function(index, item) {
                            $('#LocationDD').append($("<option>").val(item.LocationDDId).text(item.LocationDDName));
                        });
                    } else {
                      $('#LocationDD').append($("<option>").val("").text("LocationDD List Is Empty"));
                    }
                }
            });
        } else {
            $('#LocationDD').prop("disabled", true);
            $('#LocationDD').append($("<option>").val("").text("Select Location GroupDD First"));
        }
      });
    </script>
}

Hope this will solve your problem!

TanvirArjel
  • 30,049
  • 14
  • 78
  • 114
  • A poor example for many reasons. Including that if the view is returned in the post method because `ModelState` is invalid, the selections in the dropdownlists is lost and the user would need to reselect it all over again. And it cannot be used for editing existing data. –  Sep 01 '18 at 12:46
  • @StephenMuecke you are getting wrong! `Including that if the view is returned in the post method because ModelState is invalid, the selections in the dropdownlists is lost` - this is not because it will be also handle in post method properly. I have been using this for so long in many complex forms and it is working efficiently without a single propblem. – TanvirArjel Sep 01 '18 at 12:51
  • @StephenMuecke Moreover, If you have better option than this please post it here as answer so that we can also know your approach. Thank you. – TanvirArjel Sep 01 '18 at 12:52
  • Seriously? - study the code in the [DotNetFiddle](https://dotnetfiddle.net/1bPZym) I noted in the comments above for how to do it correctly (even your `return Json(LocationDDList, JsonRequestBehavior.AllowGet)` code is inefficient since its sending data to the client that is not even used (only 2 properties should be returned (for the option value and its text) –  Sep 01 '18 at 12:55
  • @StephenMuecke In our implementation we always select 2 property (key and value). But here I didn't use select because questioner didn't provide much more information. I am confidant that questioner will do that efficiently. – TanvirArjel Sep 01 '18 at 12:59
  • @StephenMuecke I have updated the answer and added the select query. Thank you for your suggestion. – TanvirArjel Sep 01 '18 at 13:08
  • That was not the main problem with your example - its the fact that the 2nd dropdown list is empty if you return the view because `ModelState` is invalid, and the poor user has to select a different option in the first to trigger loading the options in the 2nd (wasting an ajax call), and then select the correct one again to get the correct options, and then select an option in the 2nd one (even though they had already selected it before). Study the code in the DotNetFiddle :) –  Sep 01 '18 at 13:12
  • @StephenMuecke I have understood your concern. Actually till now I have handle this situation in Post method properly in case ModelState is invalid. Okay I shall read your suggested implementation. – TanvirArjel Sep 01 '18 at 13:14
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/179242/discussion-between-stephen-muecke-and-tanvirarjel). –  Sep 01 '18 at 13:15
  • @StephenMuecke I have understood what you wanted and updated my code again.Please take a deep look on it. I have also taken a look on your implementation. Functionality of both of us is same but implementation is different. Thank you again for showing the error. – TanvirArjel Sep 01 '18 at 14:29