I have three tables in my database as follows:
University
id Name
1 A
2 B
Faculty
id id_uni name
1 1 AA
2 1 AA
cafedry
id id_uni id_faculty name
1 1 1 cc
I would like to create a cascading dropdown which will allow me to first select a University then a Faculty followed by a Cafedry. Below code is what i have tried so far.
public ActionResult Create()
{
ViewBag.fak_kod = new SelectList(db.Fakulteler, "id", "adi");
ViewBag.unikod = new SelectList(db.Universitetler, "id", "adi");
return View();
}
// POST: kafedras/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "id,unikod,fak_kod,adi")] kafedra kafedra)
{
if (ModelState.IsValid)
{
db.kafedra.Add(kafedra);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.fak_kod = new SelectList(db.Fakulteler , "id", "adi", kafedra.fak_kod);
ViewBag.unikod = new SelectList(db.Universitetler, "id", "adi", kafedra.unikod);
return View(kafedra);
}
and this cshtml
<div class="form-horizontal">
<h4>kafedra</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.unikod, "unikod", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("unikod", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.unikod, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.fak_kod, "fak_kod", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("fak_kod", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.fak_kod, "", new { @class = "text-danger" })
</div>
</div>
How can update this code to create a cascading dropdown with the three tables?
See Question&Answers more detail:os