Good afternoon I have a theme, changing my combo locality does not change the neighborhood, I'm new using ajax, and I do not understand where the problem is. Thank you very much already.
The code is as follows:
On the controller:
[HttpGet]
public JsonResult GetBarrios(string LocalidadId = "")
{
List<Barrios> lBarrios = new List<Barrios>();
int Id = 0;
if (int.TryParse(LocalidadId, out Id))
{
lBarrios = db.Barrios.Where(a => a.cod_localidad.Equals(Id)).OrderBy(a => a.barrio).ToList();
}
if (Request.IsAjaxRequest())
{
return new JsonResult
{
Data = lBarrios,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else
{
return new JsonResult
{
Data = "Not valid request",
JsonRequestBehavior = JsonRequestBehavior.DenyGet
};
}
}
In the view, this is the jquery:
<script language="javascript">
$(document).ready(function () {
$("#LocalidadId").change(function () {
//Esto se llama cuando cambia la localidad
var LocalidadId = parseInt($("#LocalidadId").val());
if (!isNaN(LocalidadId)) {
var ddBarrio = $("#BarriosId");
ddBarrio.empty();
ddBarrio.append($("<option></option").val("").html("Seleccione un Barrio"));
//llamamos al controlador
$.ajax({
url: "@Url.Action("GetBarrios","Home")",
type: "GET",
data: { LocalidadId: LocalidadId },
datatype: "json",
success: function (data) {
$.each(data, function (i, val) {
ddBarrio.append(
$("<option></option>").val(val.cod_barrio).html(val.barrio)
);
});
},
error: function () {
alert("Error!");
}
});
}
});
});
</script>
And this in the combos:
<div class="form-group" >
<div label="Localidad" class="form-inline">
@Html.DropDownList(Model.Select(a => a.Barrios.cod_localidad).ToString(), @ViewBag.LocalidadId as SelectList, "Localidad")
</div>
</div>
<div class="form-group" id="frmBarrios">
<div class="form-inline">
@Html.DropDownList(Model.Select(w => w.Barrios.cod_barrio).ToString(), ViewBag.BarriosId as SelectList, "Barrio")
</div>
</div>