Hi All,
I want to populate two dropdowns in my MVC project.
First one is for countries and second one for states corresponding to the country selected in the first dropdown. But it is not loading. I couldn't find where the bug is...
In Model
public class CandidateContactUs{
public CandidateContactUs()
{statesList = new SelectList(new List<SelectListItem>(), "stateID", "state");}
public SelectList statesList { get; set; }
private int _countryID;
[Display(Name = "Country")]
public int countryID { get { return _countryID; } set { _countryID = value; } }
public SelectList countries { get { return LoadCountries();} }
private int _stateID;
[Display(Name = "State")]
public int stateID { get { return _stateID; } set { _stateID = value; } }
public IList<SelectListItem> states { get; set; }
private SelectList LoadCountries()
{TestMVC.Models.SMTestEntities objSMWebDefaultConnection = new TestMVC.Models.SMTestEntities();
var countryList = objSMWebDefaultConnection.tblCountries.Where(c => c.recordActive == true).Select(c => new { c.countryID, c.country }).ToList();
return new SelectList(countryList, "countryID", "country");}
In Controller
public ActionResult ContactUs()
{ CandidateContactUs contactUs = new CandidateContactUs();
return View(contactUs);}
TestMVC.Models.SMTestEntities objSMWebDefaultConnection = new TestMVC.Models.SMTestEntities();
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult LoadStatesList(int countryID)
{ var statesList = objSMWebDefaultConnection.tblStates.Where(s => s.recordActive == true && s.countryID == countryID).Select(s => new { s.stateID, s.state }).ToList();
return Json(statesList, JsonRequestBehavior.AllowGet);
In View
@Html.DropDownListFor(model => model.countryID, Model.countries, new { @id = "drpCountry" })
@Html.ValidationMessageFor(model => model.countryID)
<label for="stateID">
State</label>
@Html.DropDownListFor(model => model.stateID, Model.statesList, new { @id = "drpState" })
<script type="text/javascript">
$(function () {
$("#drpCountry").change(function () {
var countryID = $("#drpCountry").val();
$.ajax({
cache: false,
type: "GET",
url: '@(Url.RouteUrl("LoadStatesList"))',
data: { "countryID": countryID },
success: function (stateArray) {
if (stateArray.d != null) {
if (stateArray.d.length != 0) {
$.each(stateArray, function (id, option) {("#drpState").append($('<option></option>').val(option.stateID).html(option.state)); });
}
}
},
error: function () {
alert("Failed to load states. Please try again.");
}
});
});
});
</script>
Any one Please help me..