Hi I am creating a Cascading DropDown using MVC6 rc 1, JQuery, Ajax, JSON, the code is as below, but I got a issue with retrieving selected data from the the sub dropdown list 'Site' populated by JQuery, which return empty list from the model binding in the HTTPPost action - CreateUser()
In the view:
<div class="form-group"><label asp-for="Company" class="col-md-2 control-label"></label><div class="col-md-10"><select asp-for="Company" asp-items="ViewBag.Companies" class="form-control" onchange="FillSite()" ><option>Please select an option</option></select></div></div><div class="form-group"><label asp-for="Site" class="col-md-2 control-label"></label><div class="col-md-10"><select asp-for="Site" asp-items="ViewBag.Sites" class="form-control" ></select></div></div><div class="form-group"><div class="col-md-offset-2 col-md-10"><button type="submit" class="btn btn-default">Add User</button></div></div>
view model:
public class CreateUserViewModel { //... other user attributes public int Company { get; set; } public int[] Site { get; set; } }
In the controller action, async Task<IActionResult> CreateUser(CreateUserViewModel model), the site attribute in the binding model CreateUserViewModel return null, but company attribute returned correct select company id in the CreateUserViewModel, is that because Jquery popularted dropdown list can not be model binding to the post action?
// GET: /Account/Register [HttpGet] [AllowAnonymous] public IActionResult CreateUser() { ViewBag.Companies = new SelectList(_context.Company, "CompanyId", "CompanyName"); ViewBag.Sites = new MultiSelectList(new List<Site>(), "SiteId", "SiteName"); return View(); } // POST: [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> CreateUser(CreateUserViewModel model) { // ......Create user codes foreach (var item in model.Site) { var userSite = new ApplicationUserSite { Id = userID, SiteID = item }; _context.ApplicationUserSite.Add(userSite); await _context.SaveChangesAsync(); } return View(model); } [AllowAnonymous] public ActionResult FillSite(int company) { var sites = _context.Site.Where(a=>a.CompanyID.Equals(company)).OrderBy(a => a.SiteName).ToList(); return Json(sites); } }