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="CompanyID" class="col-md-2 control-label"></label><div class="col-md-10"><select asp-for="CompanyID" 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="SiteIDs" class="col-md-2 control-label"></label><div class="col-md-10"><select asp-for="SiteIDs" asp-items="(MultiSelectList)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>
JQuery in the view:
@section Scripts { @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }<script> function FillSite() { var companyId = $('#CompanyID').val();$.ajax({ url: '/Account/FillSite', type: "Post", dataType: "JSON", data: { Company: companyId}, success: function (sites) {$("#SiteIDs").html(""); // clear before appending new list$.each(sites, function (i, site) {$("#SiteIDs").append($('<option></option>').val(site.SiteId).html(site.SiteName)); }); } }); }</script> }
View model:
//other view model attributes
[Display(Name = "Company")] public int CompanyID { get; set; } [Display(Name = "Site")] public int[] SiteIDs{ 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); } }