C# – MVC (Razor) Filter DropDownList

asp.netasp.net-mvcasp.net-mvc-4crazor

I'm new to MVC and JavaScript and I have a question about DropDownList.

I Build a program of "Car Renting" and I have a View that allow adding new Car to the inventory.

The view include 2 dropdownlists (see below):

 <div class="editor-field">
        @Html.DropDownList("ManufacturerId", string.Empty)
        @Html.ValidationMessageFor(model => model.ManufacturerId)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.ModelId)
    </div>
    <div class="editor-field">
        @Html.DropDownList("ModelId", string.Empty)
        @Html.ValidationMessageFor(model => model.ModelId)
    </div>

I want that when user select a manufacturer for example (Alfa Romeo) the "model" list box will display only "Alfa Mito" models and not the full list…

My Controller function send to the view the Model List using ViewBag see below:

public ActionResult AddNewCar()
    {
        ViewBag.ManufacturerId = new SelectList(db.Manufacturers, "ManufacturerId", "ManufacturerName");
        ViewBag.ModelId = new SelectList(db.Models, "ModelId", "ModelName");

        ViewBag.BranchId = new SelectList(db.Branchs, "BranchId", "BranchName");

        return View();
    }

Please advice.

Thanks,
Almog

Best Answer

call below action method from jquery on dropdown change event.

 public List<carmodels> PopulateState(int manufacturerId)
        {
            var carmodelsObj = (from st in dc.Carmodels
                        where st.manufacturerId.Equals(manufacturerId)
                        select st).ToList();

            return (carmodelsObj);

        }