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;}
    
9
  • could you format your code for better readability? remove the extra empty lines, indent properly. Commented Jul 16, 2018 at 13:47
  • of course kenny sorry for that ... Commented Jul 16, 2018 at 13:50
  • much better. I add some relevant tags Commented Jul 16, 2018 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? Commented Jul 16, 2018 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 Commented Jul 16, 2018 at 14:07

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

The problem is solved and was that i need to re-populate the dropdown list in the http post

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.