Pregunta

I'm working on some search/filter functionality by using dropdownlists the question is how can i populate the second dropdownlist by choosing item in first ddl if all data saved in ont table. i have table of CarType that has manufacturer, model and year. when i choose a manufacturer in first ddl the second will filled by models of this manufacturer.

Code i have in Controller:

    public ActionResult Search(string manufacturer, string carModel, string searchString, string gear)
    {
        using (CarTypesLogic logic = new CarTypesLogic())
        {
            IEnumerable<CarType> allCarTypes = logic.GetAllCarTypes();

            var manufacturerList = new List<string>();

            var modelList = new List<string>();

            var gearList = new List<string>();

            var foundManufacturer = from maker in allCarTypes
                                    orderby maker.Manufacturer
                                    select maker.Manufacturer;



            var foundModels = from model in allCarTypes
                              orderby model.Model
                              select model.Model;

            var foundGears = from transmission in allCarTypes
                             select transmission.Gear;


            manufacturerList.AddRange(foundManufacturer.Distinct());

            modelList.AddRange(foundModels.Distinct());

            gearList.AddRange(foundGears.Distinct());




            ViewBag.Manufacturer = new SelectList(manufacturerList);

            ViewBag.Gear = new SelectList(gearList);




            ViewBag.carModel = new SelectList(modelList);

            var foundCars = from car in allCarTypes select car;

            if (!String.IsNullOrEmpty(manufacturer))
            {
                foundCars = foundCars.Where(car => car.Manufacturer == manufacturer);
            }


            if (!String.IsNullOrEmpty(gear))
            {
                foundCars = foundCars.Where(car => car.Gear == gear);
            }

            if (!String.IsNullOrEmpty(searchString))
            {
                foundCars = foundCars.Where(car => car.Manufacturer.ToLower().Contains(searchString.ToLower()));
            }

            if (!String.IsNullOrEmpty(carModel))
            {
                foundCars = foundCars.Where(car => car.Model == carModel);
            }
            return View(foundCars);
        }
    }

My cshtml code:

    @using (Html.BeginForm())
{    
    <p>
        Manufacturer: @Html.DropDownList("manufacturer", String.Empty)
        Model: @Html.DropDownList("carModel",String.Empty)
        Gear: @Html.DropDownList("gear", String.Empty)
        Free Type: @Html.TextBox("SearchString")
        <br />
        <input type="submit" value="Search"/>
    </p> 
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top