skip to Main Content

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.

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


  1. Instead of using ViewData (yuk!), bind values to public properties on your PageModel:

    public class PageNameModel : PageModel
    {
        public Dictionary<int, string> Users { get; set; } 
        [BindProperty]
        public int SelectedUserId { get; set; } = 123;
        public void OnGet()
        {
    
        }
    
        public IActionResult OnPost()
        {
            // Process form submission
            HttpContext.Session.SetString("selectedUserId", SelectedUserId.ToString());
    
            return RedirectToPage();
        }
    }
    

    Then assign the SelectedUserId property to the asp-for attribute on the select tag helper:

     <div class="rollname">
         <label class="required">User Name :</label>
         <select asp-for="SelectedUserId" class="form-control-1"
                 asp-items='@(new SelectList(Model.Users, "Key", "Value"))'
                 onchange="this.form.submit()">
             <option value="">--Select--</option>
         </select>
     </div>
    

    See more about model binding here: https://www.learnrazorpages.com/razor-pages/model-binding

    Login or Signup to reply.
  2. You could use the TempData to save the selected value. here is the sample code you could try:

    Index.cshtml:

    @page
    @model IndexModel
    @{
        ViewData["Title"] = "Home page";
    }
    <div class="rollname">
        <label class="required">User Name :</label>
        <form method="post">
            <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>
        </form>
    </div>
    

    Index.cshtml.cs:

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    
    namespace RazorPagesExample.Pages
    {
        public class IndexModel : PageModel
        {
            public Dictionary<long, string> Users { get; set; }
    
            public void OnGet()
            {
                // Load users data
                Users = GetUserList();
    
                // Retrieve selected user ID from TempData if it exists
                if (TempData.ContainsKey("SelectedUserId"))
                {
                    ViewData["SelectedUserId"] = TempData["SelectedUserId"];
                }
            }
    
            public IActionResult OnPost(long selectedUser)
            {
                // Process form submission
                HttpContext.Session.SetString("selectedUserId", selectedUser.ToString());
    
                // Store the selected user ID in TempData
                TempData["SelectedUserId"] = selectedUser.ToString();
    
                return RedirectToPage();
            }
    
            private Dictionary<long, string> GetUserList()
            {
                // Replace with your logic to get users
                return new Dictionary<long, string>
                {
                    { 1, "User1" },
                    { 2, "User2" },
                    { 3, "User3" }
                };
            }
    
        }
    }
    

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search