我只是MVC和JQuery的初学者。 我正在尝试使用Country和State创建一个简单的级联下拉列表应用程序作为两个下拉列表。我使用JQuery ajax作为脚本来处理Dropdown更改事件。
但是当我从下拉列表中选择任何国家/地区时,我的事件会正确触发,但我无法获取所选值,因为它返回“未定义”值。
任何人都可以帮助我。
我正在按照以下方式分享我的代码。
以下是控制器部分
中定义的功能public ActionResult Index()
{
return View();
}
public JsonResult GetCountries()
{
return Json(db.Countries.ToList(), JsonRequestBehavior.AllowGet);
}
public JsonResult GetStatesByCountryId(string countryId)
{
int Id = Convert.ToInt32(countryId);
var states = from a in db.States where a.CountryID == Id select a;
return Json(states);
}
以下是Index.cshtml部分
<div>
<div>
@Html.DropDownList("dropdownCountry", new SelectList(string.Empty, "Value", "Text"), "Please select a country", new { @style = "width:250px;" })
</div>
<div style="margin-top:50px;">
@Html.DropDownList("dropdownState", new SelectList(string.Empty, "Value", "Text"), "Please select a state", new { @style = "width:250px;" })
</div>
</div>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery-ui-1.8.24.min.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: "GET",
url: "/home/getcountries",
datatype: "Json",
success: function (data) {
$.each(data, function (index, value) {
$('#dropdownCountry').append('<option value="' + value.CountryId + '">' + value.CountryName + '</option>');
});
}
});
$('#dropdownCountry').change(function () {
var selectedCountryID = $('#dropdownCountry').val();
alert(selectedCountryID);
$('#dropdownState').empty();
$.ajax({
type: "POST",
url: "/home/GetStatesByCountryId",
datatype: "Json",
data: { countryId: $('#dropdownCountry').val() },
success: function (data) {
$.each(data, function (index, value) {
$('#dropdownState').append('<option value="' + value.Id + '">' + value.StateName + '</option>');
});
}
});
});
});
</script>
提前致谢