'Setting a select's selected value to "selected" after form submit and page refresh

I have an asp form handler posting form data from a select to call a database function. My functionality seems to work just fine but I need to find a way to set the posted option to "selected" after the form has been submitted. Due to the page refresh, the form just resets to its default selected value - not the posted form value.

Here is my form:

            <form method="post" asp-page-handler="location" class="location-container">

            <select class="location-picker" name="location_id" value="1">
                <option class="option1" value="1">Bloom Headquarters</option>
                <option class="option2" value="2">Peony Place</option>
                <option class="option3" value="3">Carnation Corner</option>
            </select>

            <input class="btn confirm" type="submit" value="CHANGE" style="float:left;" />
        </form>

Is there anything I can do in the backend to call the location id of the submitted form and set the select's selected value to that submitted value? Do I need to use local storage or a URL query perhaps?



Solution 1:[1]

You can use tag helper to achieve your requirement which can store the original value to ModelState:

Page:

@page
@model IndexModel        
<form method="post" asp-page-handler="location" class="location-container">
    <select class="location-picker" asp-for="location_id" value="1">
        <option class="option1" value="1">Bloom Headquarters</option>
        <option class="option2" value="2">Peony Place</option>
        <option class="option3" value="3">Carnation Corner</option>
    </select>

    <input class="btn confirm" type="submit" value="CHANGE" style="float:left;" />
</form>

PageModel:

public class IndexModel : PageModel
{
    public void OnGet()
    {
    }
    [BindProperty]
    public string location_id { get; set; }
    public void OnPostLocation()
    {      
        //do your stuff with location_id...
    }
}

Result: enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rena