nga ara

nga ara

  • NA
  • 6
  • 3.4k

Binding dropdownlist using MVC5 and json

Feb 14 2014 5:12 PM
Used Nimith Joshi's article : Working With DropDownList in MVC 5 Using jQuery
 
Issue : Not displaying "State".
 
Model.Countries : I could populate dropdownlist for "Country" from the database.
 
controller:
public JsonResult States(string Country)
{
List<string> statesList = new List<string>();
switch (Country) {
case "Canada":
statesList.Add("Quebec");
statesList.Add("Ontario");
break;
case "Australia":
statesList.Add("Melbourne");
statesList.Add("Sydney");
break;

case "UNITED STATES":
statesList.Add("New York");
statesList.Add("Washington");
break; }

return Json(statesList);
}

cshtml :
<div class="form-group">
@Html.DropDownListFor(model => model.Country, new SelectList(Model.Countries, "Key", "Value"))
</div>
<div class="form-group">
<select id="State"></select>
</div>


<script>
$(document).ready(function () {
$("#Country").change(function () {
if ($("#Country").val() != "Select") {

var CountryOptions = {};
CountryOptions.url = "/Test/States";
CountryOptions.type = "POST";
CountryOptions.data = JSON.stringify({ Country: $("#Country").val() });
CountryOptions.datatype = "json";
CountryOptions.contentType = "application/json";
CountryOptions.success = function (statesList) {

$("#State").empty();
for (var i = 0; i < statesList.length; i++) {
$("#State").append("<option>" + statesList[i] + "</option>");
}
$("#State").prop("disabled", false);
};
CountryOptions.error = function () { alert("Error in Getting States!!"); };
$.ajax(CountryOptions);
}
else {
$("#State").empty();
$("#State").prop("disabled", true);
}
});
});
</script>


 
Thanks in advance!
 

Answers (2)