[英]Cascading (Dependent) Country State City DropDownLists using jQuery AJAX in ASP.Net MVC
我需要在 ASP.Net MVC 中使用 jQuery AJAX 填充级联国家、State 和城市下拉列表。
这是教程
并且工作正常。
我的问题是在发送表单时验证这些 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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.