Copy the code that populates the list from the OnGet to the OnPost.
How to repopulate dropdown boxes when a razor page reloads in Asp .NET Core 6
I am working on a Razor page in Asp .NET Core 6. Through identity scaffolding it created a Register.cshtml page. I modified the page with input for email and user name and three dropdowns for State, Title and Salutation. I am populating the dropdowns with data from the database. Everything works fine as long as validation happens in the client side. However in the OnPostAsync method I check whether the email already exists in the database. If yes, then I add ModelState.AddModelError("Input.Email","Email already exists"). When the page is shown back again with this error, the dropdown boxes show only the selected values. The other options are gone. Because of that they can't change whatever they have already selected, since the other options are not available. Please let me know how to repopulate the dropdowns with all the available values when the razor page posts back.
Code of the InputModel calss within Register.cshtml.cs
[BindProperty]
public IEnumerable<SelectListItem> TitleList { get; set; }
[BindProperty]
public IEnumerable<SelectListItem> SalutationList { get; set; }
[BindProperty]
public IEnumerable<SelectListItem> StateList { get; set; }
How the three dropdowns are populated:
public async Task OnGetAsync(string returnUrl = null)
{
ReturnUrl = returnUrl;
var salutationList = await _registrationLists.GetSalutationAsync();
var titleList = await _registrationLists.GetTitleAsync();
var stateList = _registrationLists.GetState();
Input = new InputModel()
{
TitleList = titleList.Select(t => new SelectListItem
{
Text = t.TitleName,
Value = t.TitleID.ToString(),
}),
SalutationList = salutationList.Select(s => new SelectListItem
{
Text = s.SalutationName,
Value = s.SalutationID.ToString(),
}),
StateList = stateList.Select(st => new SelectListItem
{
Text = st.StateName,
Value = st.StateID.ToString(),
}),
};
}
Code in the OnPostAsync:
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl ??= Url.Content("~/");
if (ModelState.IsValid)
{
var userIdNew = await _personRegister.IsValidEmailAsync(Input.Email, LoginTypeEnum.External.ToString());
if (userIdNew)
{
ModelState.AddModelError("Input.Email", "The email already exits. Use a different value!");
}
if (userIdNew)
{
return Page();
}
//***********More code here ***********************
}