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
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);
}
You need to repopulate/populate your ModelId
dropdown on every time when your first dropdown changes (using jquery
). Do following:
Get the ManufactureId
from first dropdown on change event. and place an ajax
call to repopulate your second dropdown.
$("#ManufactureId").change(function() { var manufacturerId = manufacturer$('#ManufacturerId').val(); $.ajax({url: "~/Car/GetCarsByManufacturer", success: function(result){ //re populate your second dropdown here //hint: you may use response.id for value }});
});
Create a function in your controller that returns Car Models, based on selected. (call this function in previous step using ajax).
public List<carmodels> GetCarsByManufacturer(int manufacturerId) { var carmodelsObj = (from st in dc.Carmodels where st.manufacturerId.Equals(manufacturerId) select st).ToList(); return (carmodelsObj); }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.