2
I can’t get the script to work. I have to do research into the second Dropdown (Scams) and save the ID of the second dropdown to make the Post the ID in the BD
Controller: This Controller will seek the dioceses of the first dropdown.
public ActionResult GetDioceses()
{
// Obter todas as dioceses usando Entity Framework e LINQ
var dioceses = db.Diocese
.Select(d => new { d.DioceseID, d.Nome })
.OrderBy(d => d.Nome);
if (HttpContext.Request.IsAjaxRequest())
return Json(new SelectList(
dioceses,
"DioceseID",
"Nome"), JsonRequestBehavior.AllowGet
);
return View(dioceses);
}
This controller will collect all the Vigararias belonging to the diocese.
public ActionResult 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);
if (HttpContext.Request.IsAjaxRequest())
return Json(new SelectList(
vigararias,
"VigarariaID",
"Nome"), JsonRequestBehavior.AllowGet
);
return View(vigararias);
}
View:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$.getJSON("@Url.Action("GetDioceses", "Paroquia")"
var items = "<option>---------------------</option>";
$.each(data, function (i, diocese) {
items += "<option value='" + diocese.Value + "'>" + diocese.Text + "</option>";
});
$("#Dioceses").html(items);
});
$("#Dioceses").change(function () {
$.getJSON("@Url.Action("GetVigarariasByDioceses", "Paroquia")/"+ $("#Dioceses > option:selected").attr("value"), function (data) {
var items = "<option>---------------------</option>";
$.each(data, function (i, vigararia) {
items += "<option value='" + vigararia.Value + "'>" + vigararia.Text + "</option>";
});
$("#Vigararias").html(items);
});
});
});
</script>
<div class="form-group">
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-group">
@Html.Label("Dioceses", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-3">
<select id="Dioceses" name="Dioceses" class="form-control"></select>
</div>
</div>
<div class="form-group">
@Html.Label("Vigararias", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-3">
<select id="Vigararias" name="Vigararias" class="form-control"></select>
</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>
</div>
}
Your doubt is what you pass to
$.getJSON()
?– Leonel Sanches da Silva
Yes that’s my question.
– Simão Lopes
I’ve made changes to the script
– Simão Lopes