我需要在ASP.Net MVC中使用jQuery AJAX填充级联国家,州和城市DropDownLists。
这是教程
并正常工作。
我的问题是发送表单时验证这些DropDownList
@Html.DropDownListFor(m => m.CountryId, Model.Countries, "[ === Select CountryId === ]", new { @Class = "textarea" })
@Html.ValidationMessageFor(m => m.CountryId, "", new { @class = "text-danger" })
@Html.DropDownListFor(m => m.StateId, Model.States, "[ === Select StateId === ]", new { @Class = "textarea" })
@Html.ValidationMessageFor(m => m.StateId, "", new { @class = "text-danger" })
此时,如果在DropDownList上未选择任何值,则该表单有效。
该如何解决呢?
我的视图javascript部分跟随
@section Scripts {
<script src="https://code.jquery.com/jquery-1.10.2.js"
integrity="sha256-it5nQKHTz+34HijZJQkpNBIHsjpV8b6QzMJs9tmOBSo="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(function () {
$("select").each(function () {
if ($(this).find("option").length <= 1) {
$(this).attr("disabled", "disabled");
}
});
$("select").change(function () {
var value = 0;
if ($(this).val() != "") {
value = $(this).val();
}
var id = $(this).attr("id");
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: '{type: "' + id + '", value: "' + value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var dropDownId;
var list;
switch (id) {
case "CountryId":
list = response.States;
DisableDropDown("#StateId");
DisableDropDown("#CityId");
PopulateDropDown("#StateId", list);
break;
case "StateId":
dropDownId = "#CityId";
list = response.Cities;
DisableDropDown("#CityId");
PopulateDropDown("#CityId", list);
break;
}
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
function DisableDropDown(dropDownId) {
$(dropDownId).attr("disabled", "disabled");
$(dropDownId).empty().append('<option>[ === Select CountryId === ]</option>');
}
function PopulateDropDown(dropDownId, list) {
if (list != null && list.length > 0) {
$(dropDownId).removeAttr("disabled");
$.each(list, function () {
$(dropDownId).append($("<option></option>").val(this['Value']).html(this['Text']));
});
}
}
</script>
}
为什么不执行这样的事情:
if ($(this).val() == "") {
// return validation message
return;
}
else
{
value = $(this).val();
}