我告訴過你我的評論,你可以使用jQuery和它的級聯下拉插件,但如果你仍然想使用香草JS,你可以做這樣的事情:
HTML:
<select id="club" name="ClubId">
<option selected="selected" value="?">Select a club</option>
<option value="1">Club 1</option><!-- value is the ClubId -->
<option value="2">Club 2</option>
<option value="3">Club 3</option>
</select>
<select id="sport" name="SportId">
<option value="?">Select a club first</option>
</select>
JS:
var clubSelect = document.getElementById("club");
var sportSelect = document.getElementById("sport");
var resetSportsOptions = function() {
sportSelect.options.length = 1;
if (clubSelect.value == "?") {
sportSelect.options[0].text = "Select a club first ";
} else {
sportSelect.options[0].text = "Select a sport ";
}
}
var addSportOption = function (sport) {
var option = document.createElement("option");
option.text = sport.Name;
option.setAttribute("value", sport.SportId);
sportSelect.add(option);
}
var sendAjaxRequest = function() {
var r = new XMLHttpRequest();
r.open("POST", "/Sports/InClub", true);
r.onreadystatechange = function() {
if (r.readyState != 4 || r.status != 200)
return;
var sports = JSON.parse(r.responseText);
for (var i = 0; i < sports.length; ++i) {
addSportOption(sports[i]);
}
};
r.send("clubId=" + sportSelect.value);
}
clubSelect.addEventListener("change", function() {
resetSportsOptions();
if (clubSelect.value != "?") {
sendAjaxRequest();
}
});
ASP.NET MVC:
public class SportsController : Controller{
// Your usual code
public ActionResult InClub(int clubId){
var sports = from s in db.Sport
join sic in db.SportInClub on s.SportId = sic.SportId
where sic.ClubId == ClubId
select s
return Json(sports);
}
}
你使用任何JavaScript庫? – Groyoh 2014-10-30 17:29:32
目前還沒有 – Smaribaldurs 2014-10-31 14:42:31
那麼,如果你不介意使用它,你可以使用JQuery和它的級聯下拉插件。檢查[這裏](https://github.com/dnasir/jquery-cascading-dropdown)插件。 – Groyoh 2014-11-01 14:27:15