Always enter the ajax error:
error: function (ex) {
alert('Failed to retrieve vigararias.' + ex);
}
Screen Error:
Failed to retrieve cheaters. [object Object]
View:
<script type="text/javascript">
$(document).ready(function () {
//Dropdownlist Selectedchange event
$("#Dioceses").change(function () {
$("#Vigararias").empty();
$.ajax({
type: 'POST',
url: '@Url.Action("GetVigarariasByDioceses", "Paroquia")', // chamar o metodo em json
dataType: 'json',
data: { id: $("#Dioceses").val() },
success: function (vigararias) {
$.each(vigararias, function (i, vigararia) {
$("#Vigararias").append('<option value="' + vigararia.Value + '">' + vigararia.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve vigararias.' + ex);
}
});
return false;
})
});
</script>
<div class="form-group">
@Html.Label("Dioceses", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-3">
@Html.DropDownList("Dioceses", (SelectList)ViewBag.dioceses, "--Escolha uma diocese--", htmlAttributes: new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.Label("Vigararias", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-3">
@Html.DropDownList("Vigararias", new SelectList(string.Empty, "VigarariaID", "Nome"), "--Escolha uma Vigararia--", htmlAttributes: new { @class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Criar" class="btn btn-primary" />
</div>
Controller:
public ActionResult CriarParoquia()
{
ViewBag.Dioceses = new SelectList(db.Diocese, "DioceseID", "Nome");
return View();
}
public JsonResult GetVigarariasByDioceses(int DioceseId)
{
// Obter Vigararias de uma Diocese utilizando LINQ.
var vigararias = db.Vigararia
.Where(v => v.DioceseID == DioceseId)
.Select(v => new { v.VigarariaID, v.Nome })
.OrderBy(v => v.Nome);
return Json(new SelectList(vigararias,"VigarariaID","Nome"));
}