这是我的 JavaScript:
<script type="text/javascript">
$(function () {
$("select#City_DDL_ID").change(function (evt) {
if ($("select#City_DDL_ID").val() != "-1") {
$.ajax({
url: "/Home/GetHotels",
type: 'POST',
dataType: "json",
data: { id: $("select#City_DDL_ID").val() },
success: function (response) {
// $('#Hotel_DDL_ID').attr('disabled', false);
$("select#Hotel_DDL_ID").replaceWith(response);
},
error: function (xhr) {
alert("Something went wrong, pleae try again");
}
});
}
});
});
这是 Index.cshtml:
@model RoomReservation.Webb.Models.HomeViewModel
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<fieldset>
<legend>Select a city and a hotel</legend>
<br />
<br />
<br />
@Html.DropDownListFor(x=>x.City_DDL_ID, new SelectList(Model.AllCities, "Value", "Text"),"...pick a city..." )
<br />
<br />
@Html.DropDownListFor(x => x.Hotel_DDL_ID, Enumerable.Empty<SelectListItem>(), "...pick a hotel...", new { disabled = "disabled"})
<br />
<br />
</
fieldset>
这是ajax调用的方法:
public JsonResult GetHotels(int id)
{
if (id > 0)
{
var hotels = bl.ReturnAllHotelsInCity(id);
return Json(hotels);
}
else
{
throw new Exception("Hotel not reachable, please try again");
}
}
在 City_DDL_ID 中选择城市后,我的 Hotel_DDL_ID 消失。你能帮帮我吗,我是 javasrcipt 和 ajax 的新手?
这是 newset 脚本,但仍然无法正常工作:
<script type="text/javascript" language="javascript">
$('#City_DDL_ID').change(function () {
var selectedCity = $(this).val();
if (selectedCity != null && selectedCity != '-1') {
$.getJSON('@Url.Action("GetHotels")', { id: selectedCity }, function (hotels) {
var hotelsSelect = $('#Hotel_DDL_ID');
hotelsSelect.empty();
$.each(hotels, function (index, hotel) {
hotelsSelect.append($('<option/>',
{
value: hotel.Value,
text: hotel.Text
}));
});
$('#Hotel_DDL_ID').attr('disabled', false);
});
}
});
</script>
那么该怎么办?
谢谢大家的帮助,我的这个最新脚本正在运行,我将默认浏览器更改为 Chrome。再次感谢大家 干杯
PS 管理员:如何将问题标记为已回答?