问题描述
我在页面上有两个控件,一个用于国家/地区,另一个用于州。更改国家/地区下拉列表后,我将使用此 AJAX 函数返回州或省。我想将所有 ValidationMessageFor 和 selectedStateId 保留在控件中,只是想填充下拉列表。有没有办法为选择控件添加选项值?任何帮助都会很棒。
查看
<div class="col-md-6">
@Html.LabelFor(model => model.selectedStateId)
@Html.DropDownListFor(
x => x.selectedStateId,new SelectList("","StateId","Name"),"-- please select a States or Provincese --",new { id = "ddlStates",@class = "form-control" })
@Html.ValidationMessageFor(x => x.selectedCountryId,"",new { @class = "text-danger" })
</div>
js
$("#ddlCountry").change(function () {
var countryId = $(this).val();
console.log(countryId);
loadstates(countryId);
});
function loadstates(countryId) {
var strUrl = '@Url.Action("GetStates","RequestForm")';
$.ajax({
url: strUrl,type: "GET",dataType: "html",data: {countryId: countryId},success: function (data) {
console.log(data);
$("#ddlStates").html($(data).html());
},error: function (result) {
alert("error occured");
}
});
}
解决方法
对于级联下拉列表,我们通常在 ajax 中返回一个列表,并将它们放入选项中,并使用 append()
将选项放入下拉列表中(正如 Swati 所说)。这是一个工作演示:
查看:
<form>
<select id="ddlCountry">
<option value="1">Country1</option>
<option value="2">Country2</option>
<option value="3">Country3</option>
</select>
<div class="col-md-6">
@Html.LabelFor(model => model.selectedStateId)
@Html.DropDownListFor(
x => x.selectedStateId,new SelectList("","StateId","Name"),"-- please select a States or Provincese --",new { id = "ddlStates",@class = "form-control" })
@Html.ValidationMessageFor(x => x.selectedCountryId,"",new { @class = "text-danger" })
</div>
</form>
js:
$("#ddlCountry").change(function () {
var countryId = $(this).val();
console.log(countryId);
loadstates(countryId);
});
function loadstates(countryId) {
var strUrl = '@Url.Action("GetStates","RequestForm")';
$.ajax({
url: strUrl,type: "GET",data: {countryId: countryId},success: function (data) {
$.each(data,function (index,value) {
var text1 = '<option value=' + value.stateId + '>' +
value.name+
'</option>';
$("#ddlStates").append(text1);
});
},error: function (result) {
alert("error occured");
}
});
}
</script>
型号:
public class Address {
public int selectedStateId { get; set; }
public int selectedCountryId { get; set; }
}
public class State
{
public int StateId { get; set; }
public string Name { get; set; }
}
Action(我用假数据测试):
public List<State> GetStates(int countryId)
{
List<State> states = new List<State> { new State { StateId = 1,Name = "state1" },new State { StateId = 2,Name = "state2" },new State { StateId = 3,Name = "state3" } };
return states;
}