Click here to Skip to main content
15,942,964 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I work on an ASP.NET Core razor page. I need to retain value of address on the page after submit, because I check value of Address after submit - it is not retained, and becomes null.

I need to retain the value of the Address without resetting, using any way without using session or cookies . How to do that please?

What I have tried:

<form method="post">
    <label for="Address">Address:</label>
    <input type="text" id="Address" name="Address" value="@Model.Address" />

    <input type="submit" value="Submit" />
</form>
In my page model, what do I to do to retain the value of Address without using session or cookies?

public class TestFormModel : PageModel
{
    [BindProperty]
    public string Address { get; set; }

    public void OnGet()
    {
       // what do I need to write here to retain 
       // value of Address without using session or cookies
    }

    public IActionResult OnPost()
    {
       // what do I need to write here to retain 
       // value of Address  using session or cookies
    }
}
Posted
Updated 6-Jul-23 23:19pm

1 solution

You can pass the value as a query parameter in the form submission. a Step-by-step can be followed at - How to pass parameters to action methods in ASP.NET Core MVC[^]

Create a C# function that will hold, request and redirect the address value -
C#"
public class TestFormModel : PageModel
{
    [BindProperty]
    public string Address { get; set; }

    public void OnGet()
    {
        // Retrieve the Address value from the query parameter
        Address = Request.Query["Address"];
    }

    public IActionResult OnPost()
    {
        // Retrieve the Address value from the form submission
        Address = Request.Form["Address"];

        // Redirect to the same page with the Address value as a query parameter
        return Redirect($"/TestForm?Address={Uri.EscapeDataString(Address)}");
    }
}


In Razor -
HTML
<form method="post" asp-page="/TestForm" asp-route-Address="@Model.Address">
    <label for="Address">Address:</label>
    <input type="text" id="Address" name="Address" value="@Model.Address" />

    <input type="submit" value="Submit" />
</form>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900