最后让我的级联下拉列表工作,但发现它不是在编辑模式下重新填充。第一个下拉列表填充,我已将jquery设置为在下拉列表更改或文档就绪时运行。我在jquery中设置了一个警报,但它没有进入控制器中的函数来下拉第二个下拉列表的相应列表。谁知道我可能会出错?
以下是代码 - 基本上我正在做的是选择一家航空公司,然后从那里选择与该航空公司相关的航班列表: 视图:
<div class="editor-field">
@Html.DropDownListFor(x => x.FlightTime.AirlineID, Model.Airlines, "Select Airline")
@Html.ValidationMessageFor(model => model.AirlineID)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.FlightID, "Flight")
</div>
<div class="editor-field">
@Html.DropDownListFor(x => x.FlightTime.FlightID, Model.Flights, "Select Flight")
<a href="#" class="flight">Add new</a>
@Html.ValidationMessageFor(model => model.FlightTime.FlightID)
</div>
etc...
jQuery in View
$(document).ready(function () {
var id = $('select#FlightTime_AirlineID').val();
populate(id);
$("#FlightTime_AirlineID").change(function () {
var id = $('select#FlightTime_AirlineID').val();
populate(id);
});
function populate(id) {
alert('hello');
//The line below is where it stops
$.get('../FlightTime/GetFlightList/' + id, function (response) {
var flights = $.parseJSON(response);
var ddlSelectedFlight = $("#FlightTime_FlightID");
// clear all previous options
$("#FlightTime_FlightID > option").remove();
// populate the products
for (i = 0; i < flights.length; i++) {
ddlSelectedFlight.append($("<option />").val(flights[i].Value).text(flights[i].Text));
}
if (flights.length == 0) {
ddlSelectedFlight.append($("<option />").val('').text('No flights added'));
}
});
}
});
它应该进入的控制器功能:
public string GetFlightList(string id)
{
var flightList = this.GetFlights(Convert.ToInt32(id));
var myData = flightList.Select(a => new SelectListItem()
{
Text = a.FlightNumber,
Value = a.FlightID.ToString()
});
string text = new JavaScriptSerializer().Serialize(myData);
return text;
}
视图模型
public class FlightTimeViewModel
{
private List<SelectListItem> _airlines = new List<SelectListItem>();
private List<SelectListItem> _flights = new List<SelectListItem>();
[DisplayName("Airline")] //Selected Value
[Required(ErrorMessage = "Please select an airline")]
public string AirlineID { get; set; }
[DisplayName("Flight")] //Selected Value
[Required(ErrorMessage = "Please select a flight")]
public string FlightID { get; set; }
public List<SelectListItem> Flights
{
get { return _flights; }
}
public List<SelectListItem> Airlines
{
get
{
foreach (Airline a in TimeTable.Repository.AirlineRepository.GetAirlineList())
{
_airlines.Add(new SelectListItem() { Text = a.AirlineName.ToString(), Value = a.AirlineID.ToString() });
}
return _airlines;
}
}
public FlightTime FlightTime { get; set; }
}
该功能在创建模式下正常工作,但在处于编辑模式时的警报之后停止在jQuery行中。一直在与Viewmodels /下拉列表进行斗争,但我想在此之前已经弄明白了。
由于
答案 0 :(得分:1)
请你试试:
$("#FlightTime_AirlineID").change(function () {
var id = $('select#FlightTime_AirlineID').val();
populate(id);
}).change();