BenTen
BenTen

Reputation: 403

Saving a search string to use in other cshtml pages in ASP.NET Core Web Application

I am trying to save input (an address) from an html form in order to use in other cshtml pages in my asp.net core web application. I am also using Razor as a template language. I have a web application in which the user will enter an address on one page and then on another page I want to use that input and place it into an api call. My html form is below.

    <form method="post" action="/Features">
        <p>
            Address: <input type="text" name="searchString"/>
            <input type="submit" value="Search" />
        </p>
    </form>

I have previously used sessions but it was for an asp.net project using web forms (I believe) and am not sure if this is the route I should go. The address being entered doesn't need to be kept secure. Thanks for any help.

Upvotes: 0

Views: 717

Answers (2)

Yiyi You
Yiyi You

Reputation: 18199

Here is a demo to use TempData in Razor page:

cshtml:

<form method="post" asp-page-handler="Features">
        <p>
            Address: <input type="text" name="searchString"/>
            <input type="submit" value="Search" />
        </p>
    </form>

cshtml.cs:

 public IActionResult OnPostFeatures(string searchString) {
                TempData["searchString"] = searchString;
                xxxxxxx
            }

Other Page you want to use searchString:

string searchString=TempData["searchString"];
//TempData.Keep(); can help you keep the value,and you can still use the searchString value in other place
TempData.Keep();

or you can use

string searchString=TempData.Peek("searchString");

So that you can still keep the searchString value

Upvotes: 0

HMZ
HMZ

Reputation: 3127

You have two options here:

  1. Submit the form to your page, store the address in TempData then redirect to the second page where you would use your submitted value (Here you use the Post/Redirect/Get pattern in order to avoid your form being submitted again by mistake via a page reload).
  2. Submit the form directly to the second page.

Going with the first option is recommended.

Page:

<form method="post" asp-page-handler="Features">
    <p>
        Address: <input type="text" name="searchString"/>
        <input type="submit" value="Search" />
    </p>
</form>

Handler:

public IActionResult OnPostFeatures(string searchString)
{
    TempData["Key"] = searchString;
    return RedirectToPage("/SecondPage");
}

Then on your second page you get the searchString in the same way via:

string value = TempData["Key"] as string;

As i said you can also submit your form to the second page where you can do what ever you want with your value. Just be careful of multiple submissions.

Upvotes: 1

Related Questions