简体   繁体   中英

asp.net core mvc dropdownlist is set to null when POST of Submit button

Hello guys i have a problem with dropdownlist. For the first time i am binding the data to the Dropdownlist from the database and it works fine up to that point. When i am submitting the form(click register button)for the second time it automatically returning null value.

First time when dropdownlist is filled with data

填写下拉列表时的照片1

Second time after i pressed create button and dropdownlist is null

照片2当我提交表单并且下拉列表为空时

  • Controller Code:

     // GET method [HttpGet] [Authorize] public IActionResult Register(string returnUrl = null) { ViewData["RoleId"] = new SelectList(_MedicalCenterOrdinanceContext.AspNetRoles,"Id","Name"); return View(); } // POST method [HttpPost] [Authorize] [ValidateAntiForgeryToken] public async Task<IActionResult> Register([Bind("Username,NameAndTitle,Password,RoleId")] RegisterViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Username, NameAndTitle = model.NameAndTitle, }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { var role = _userRoles.GetRole(model.RoleId); var userAddedToRole = await _userManager.AddToRoleAsync(user, role.Name); if (userAddedToRole.Succeeded) { _logger.LogInformation("User created a new account with password."); TempData["RegisterUserPassed"] = "Succesfully created account"; } } else { model.InvalidCredentials = "This Username already exist !"; TempData["RegisterUserFailed"] = "This Username already exist"; } } // Redisplay form ModelState.Clear(); return View(); } 
  • View code :

     <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-book"></i></span> <select asp-for="RoleId" class="form-control" asp-items="@ViewBag.RoleId"></select> </div> <br /> <button type="submit" class="col-lg-12 col-md-12 col-sm-12 col-xs-12 btn btn-lg btn-primary">Create</button> <h4 hidden class="col-lg-12 col-md-12 col-sm-12 col-xs-12 text-danger " text-danger">@Html.DisplayFor(model => model.InvalidCredentials)</h4> </form> </div> 
  • Model code :

     [Required(ErrorMessage = "Username is required")] [DataType(DataType.Text)] public string Username { get; set; } [Required(ErrorMessage ="Name and Title is required")] public string NameAndTitle { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2}.", MinimumLength = 4)] [DataType(DataType.Password)] public string Password { get; set; } public string InvalidCredentials { get; internal set; } public string RoleId { get; set; } public List<SelectListItem> Roles { get; set;} 

Because on POST the form is regenerated on the server when you return View();

You need to re-populate the dropdown list in the [HttpPost] Action aswell before returning the View.

ie This line

ViewData["RoleId"] = new SelectList(_MedicalCenterOrdinanceContext.AspNetRoles,"Id","Name");

Try adding this line before return View in the HttpPost method. Like this -

....
ViewData["RoleId"] = new SelectList(_MedicalCenterOrdinanceContext.AspNetRoles,"Id","Name");
// Redisplay form
ModelState.Clear();
return View();

Also if you want the data to be restored after the Create Method is executed you must pass back your Model to the View.

ViewData["RoleId"] = new SelectList(_MedicalCenterOrdinanceContext.AspNetRoles,"Id","Name");
// Redisplay form
ModelState.Clear();
return View(model); // HERE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM