For cascading dropdown lists,we usually return a list in ajax,and put them into option,and put options to dropdownlist with append()
(As Swati says).Here is a working demo:
View:
<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>
Model:
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(I use fake data to test):
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;
}
result:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…