I have a Razor Page in ASP.NET Core where I have a dropdown list () populated with usernames. Upon selecting a username, the form is automatically submitted using JavaScript (onchange="this.form.submit()"). However, after the form submission, the selected username is cleared from the dropdown, which is not the intended behavior.
Razor Page (.cshtml):
<div class="rollname">
<label class="required">User Name :</label>
<select id="selectedUser" name="selectedUser" class="form-control-1"
asp-items='@(new SelectList(Model.Users, "Key", "Value",ViewData["SelectedUserId"]))'
onchange="this.form.submit()">
<option value="">--Select--</option>
</select>
</div>
Razor page (cshtml.cs)
public class PageNameModel : PageModel
{
public Dictionary<long, string> Users { get; set; } // Replace with actual data type
public void OnGet()
{
// Load users data and set default selected user ID
ViewData["SelectedUserId"] = "123"; // Replace with your logic to get default selected user ID
}
public IActionResult OnPost(long selectedUser)
{
// Process form submission
HttpContext.Session.SetString("selectedUserId", selectedUser.ToString());
ViewData["SelectedUserId"] = selectedUser.ToString();
return RedirectToPage();
}
}
Above is the picture for demonstration for username not getting preselected after submission
Note: There is a dropdown which is not visible in the video due to unknown reason.
How do I make sure that after selecting username dropdown value , it should not get cleared after Redirecting to same page . Is there a better approach towards this ?
2
Answers
Instead of using
ViewData
(yuk!), bind values to public properties on yourPageModel
:Then assign the
SelectedUserId
property to theasp-for
attribute on theselect
tag helper:See more about model binding here: https://www.learnrazorpages.com/razor-pages/model-binding
You could use the TempData to save the selected value. here is the sample code you could try:
Index.cshtml:
Index.cshtml.cs: