【发布时间】:2023-03-17 16:21:02
【问题描述】:
我正在尝试使用 @Html.DropDownListFor helper 和 jQuery AJAX 创建级联下拉列表。第一次加载总是完美的。所有下拉列表数据均已正确显示。但是,回发后,它总是命中 ModelState.IsValid = False 并且下拉列表变为空。以下是我的代码:
型号
Public Property Province As New List(Of SelectListItem)
Public Property City As New List(Of SelectListItem)
Public Property SelectedProvince As String
Public Property SelectedCity As String
控制器
Public Function SetEmployeeProfile() As ActionResult
Dim loc As New clsLocation
Dim provinces As List(Of Province)
Dim model As New SetEmployeeProfileViewModel
provinces = loc.GetProvinceList
Dim sel As SelectListItem
For Each p As Province In provinces
sel = New SelectListItem
sel.Text = p.ProvinceName
sel.Value = p.ProvinceName
model.Province.Add(sel)
Next
Return View(model)
End Function
查看
@ModelType SetEmployeeProfileViewModel
<div class="form-group">
@Html.LabelFor(Function(m) m.Province, New With {.class = "col-md-2 control-label"})
<div class="col-md-10">
@Html.DropDownListFor(Function(m) m.Province, New SelectList(Model.Province, "Value", "Text", Model.SelectedProvince), New With {.class = "form-control"})
@Html.ValidationMessageFor(Function(m) m.Province, "", New With {.class = "text-danger"})
</div>
</div>
<div class="form-group">
@Html.LabelFor(Function(m) m.City, New With {.class = "col-md-2 control-label"})
<div class="col-md-10">
@Html.DropDownListFor(Function(m) m.City, New SelectList(Model.City, "Value", "Text", Model.SelectedCity), New With {.class = "form-control"})
@Html.ValidationMessageFor(Function(m) m.City, "", New With {.class = "text-danger"})
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
LoadCities();
});
$("#Province").change(function () {
LoadCities();
});
function LoadCities() {
var selectedItem = $("#Province").val();
var ddlCities = $("#City");
var statesProgress = $("#city-loading-progress");
statesProgress.show();
$.ajax({
cache: false,
type: "POST",
url: "@(Url.Action("GetCities"))",
data: { "provinceName": selectedItem },
success: function (data) {
ddlCities.html('');
$.each(data, function (id, option) {
ddlCities.append($('<option></option>').val(option.CityName).html(option.CityName));
});
statesProgress.hide();
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve cities.');
statesProgress.hide();
}
});
}
注意:我尝试在模型中添加 selectedProvince 属性并根据此post 实现,但问题仍然存在。省和市字段也会产生以下验证错误:
The value 'Bali' is invalid. (Province)
The value 'Kuta' is invalid. (City)
输入查询字符串是否正常:Province=System.Collections.Generic.List?
【问题讨论】:
标签: asp.net asp.net-mvc vb.net razor