First of all, I would get rid of the ViewBag in order to transfer data (for Dropdownlist) from the controller to View. I would add that this is a property of my ViewModel.
public class ProductSale { public IEnumerable<SelectListItem> Products{ get; set; } public int SelectedProduct { get; set; } public IEnumerable<SelectListItem> SaleNumbers{ get; set; } public int SelectedSaleNumber { get; set; }
Now in my GET action I installed the Products collection and send it to the View,
public ActionResult Add() { var vm=new ProductSale(); //The below code is hardcoded for demo. you mat replace with DB data. vm.Products= new[] { new SelectListItem { Value = "1", Text = "Product A" }, new SelectListItem { Value = "2", Text = "Dealer B" }, new SelectListItem { Value = "3", Text = "Product C" } }; return View(vm); }
And in your highly typed view
@model ProductSale @using(Html.Beginform()) { @Html.DropDownListFor(x => x.SelectedProduct, new SelectList(Model.Products, "Value", "Text"), "Select Product") @Html.DropDownListFor(x => x.SelectedSaleNumber, new SelectList(Model.SaleNumbers, "Value", "Text"), "Select Number to sell") <input type="submit" /> }
Now we need some javascript to load numbers for sale when the user selects one product from the drop-down list. We will include the jQuery library in this view (or layout view), and we will add this java script to our view.
<script type="text/javascript"> $(function () { $("#SelectedProduct").change(function () { var self = $(this); var items=""; $.getJSON("@Url.Action("GetSaleNumbers","Product")/"+self.val(), function(data){ $.each(data,function(index,item){ items+="<option value='"+item.Value+"'>"+item.Text +"</option>"; }); $("#SelectedSaleNumber").html(items); }); }); }); </script>
What he does, he listens to the change event of the first dropdown list and when it happens, he gets a GET call using the getJSON method (recorded in the jquery library that we included) and get the results in JSON and JSON it and add to the second drop down list .
Assuming GetSaleNumbers is an action method in the Product controller that takes a product identifier and sends all the product numbers for this product in JSON .
public ActionResult GetSaleNumbers(int id) { List<SelectListItem> saleNumbers=new List<SelectListItem>(); //The below code is hardcoded for demo. you mat replace with DB data //based on the input coming to this method ( product id) saleNumbers.Add(new SelectListItem { Value="1" , Text="1" }, new SelectListItem { Value="2" , Text="2" }, new SelectListItem { Value="3" , Text="2" } ); return Json(saleNumbers,JsonRequestBehavior.AllowGet); }