在您的情况下,您在更改品牌下拉框时需要进行 ajax 调用或服务器调用。
请参阅下面的示例,它只是使用静态数据来识别品牌模型何时更改,然后使用 jquery(客户端)自动更改模型下拉列表。
查看端:-
@*Display the elements in the page*@
@*------------------------------------------------*@
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<div class="form-group">
<div class="col-md-10">
@Html.DropDownList("Brand", (SelectList)ViewBag.Brand, new { htmlAttributes = new { @class =
"form-control" } })
</div>
</div>
<div class="form-group">
<div class="col-md-10">
@Html.DropDownList("IdModel", (SelectList)ViewBag.IdModel, new {htmlAttributes = new {
@class = "form-control" } })
</div>
</div>
@*------------------------------------------------*@
@*Script for call the server side function when you changed brand combo from jquery*@
@*------------------------------------------------*@
<script type="text/javascript">
$(function () {
$("#Brand").change(function () {
var selectedItem = $(this).val();
$.ajax({
cache: false,
type: "GET",
url: "/Home/GetModelFromBrand", // User your action and controller name
data: { "Brandid": selectedItem },
success: function (data) {
$("#IdModel").empty();
$.each(data, function (id, option) {
$("#IdModel").append($('<option>
</option>').val(option.IdModel).html(option.Descriptive));
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve states.');
}
});
});
});
</script>
@*------------------------------------------------*@
控制器端:-
//Get Method to load the view
//==============================================================
public ActionResult Index()
{
var brands = new SelectList(new[]
{
new {Libel="Brand1",},
new {Libel="Brand2",},
},
"Libel", "Libel");
//=======Suppose Brand1 have idmodels1 , idmodels2 models
var idmodels = new SelectList(new[]
{
new {IdModel="1",Descriptive="idmodels1",},
new {IdModel="2",Descriptive="idmodels2",},
},
"IdModel", "Descriptive");
ViewBag.Brand = brands;
ViewBag.IdModel = idmodels;
return View();
}
//==============================================================
//Get Action when changed brand combo
//==============================================================
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetModelFromBrand(string Brandid)
{
var obj = new[] {
new {IdModel = 3,
Descriptive = "idmodels3"},
new {IdModel = 4,
Descriptive = "idmodels4"},
new {IdModel = 5,
Descriptive = "idmodels5"}
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
//==============================================================