2

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

Photo 1 when dropdownlist is filled

Second time after i pressed create button and dropdownlist is null

Photo 2 when i submit the form and dropdown list is null

  • 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;}
    
  • could you format your code for better readability? remove the extra empty lines, indent properly. – kennyzx Jul 16 '18 at 13:47
  • of course kenny sorry for that ... – KSProgrammer Jul 16 '18 at 13:50
  • much better. I add some relevant tags – kennyzx Jul 16 '18 at 13:58
  • So let me get this straight. You click the 'Create' button and it goes off to the controller then (i'm guessing it comes back) comes back and when you click it again theres no value in there? – JamesS Jul 16 '18 at 14:04
  • @JamesS yeap when i load for the first time view dropdownlist is already filled with data . After i create a new user and click 'Create' button data are sent to database correct but dropdownlist is null this time – KSProgrammer Jul 16 '18 at 14:07
  • How are you calling the controller when you create? – JamesS Jul 16 '18 at 14:08
  • Please check [this question](https://stackoverflow.com/questions/34223736/maintaining-viewbag-values-while-posting-data) which explains viewbag does not survive request. – kennyzx Jul 16 '18 at 14:25
  • @kennyzx the problem was that i filled dropdownlist on the httpget and didnt "re-populate" dropdownlist on the httppost so it was null – KSProgrammer Jul 16 '18 at 14:38
  • Yes... the accepted answer is correct. I find the link explains _why_ ViewData becomes null in httppost (so you have to set ViewData again), hope it helps. – kennyzx Jul 16 '18 at 14:43

1 Answers1

2

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.

i.e. 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
Dawood Awan
  • 7,051
  • 10
  • 56
  • 119