0

When the OnGetLendConfirm() executes, the url is being set to null and I don't know how to preserve the variable correctly so that I can use it in both functions.

 MongoDBHandler handler = new MongoDBHandler();
    public string url;
    [BindProperty]
    public string product { get; set; }
    public void OnGet()
    {
        url = HttpContext.Request.Query["product"].ToString();
        product = handler.CheckItems(url);
    }

    public void OnGetLendConfirm(string dt)
    {
        Debug.WriteLine(url);
        Debug.WriteLine(dt);
        //handler.LendItem(id, dt);
    }
}

1 Answers1

1

You're going to want to preserve the state of the url field with one of the available options. some options are

  • TempData
  • Hidden Form Fields
  • Querystrings
  • Route Data
  • Cookies
  • Session Variables
  • Application Variables
  • One of the available Caching strategies, like the MemoryCache class

Perhaps the easiest one to implement in your example would be to set the url as TempData field on the model with a getter and setter, which should make it available for your subsequent LendConfirm Get Request

[TempData]
public string url { get; set; }

TempData values expire as soon as you read them, so if you want to retain that value for multiple subsequent requests, you could update the LendConfirm like this:

public void OnGetLendConfirm(string dt)
{
    Debug.WriteLine(TempData.Peek("url"));
    Debug.WriteLine(dt);
    //handler.LendItem(id, dt);
}
pthomson
  • 655
  • 1
  • 6
  • 11
  • First of all, thanks, it works somewhat. For some reason it only works every second time. Meaning: the one time it works perfectly, the other time it is null, the next time it works again and so on. I have never worked with TempData, so am I missing something here? – cryptosight May 31 '22 at 20:06
  • TempData will expire as soon as you read it. If you need to hold on to that value for longer than one additional round trip to the server, you can use .Peek() to retrieve the value without expiring it. Or .Keep() to keep it from expiring. This [post](https://stackoverflow.com/questions/21252888/tempdata-keep-vs-peek) helps explain ... or Session variable may be more what you want if you want to hang on to that value for multiple requests. But if you're using .NET Core, like Razor pages, then session will have to be added, as it is now _opt-in_ .. – pthomson May 31 '22 at 20:19
  • Thank you so much, with .Peek() it's working just as i need it to. – cryptosight May 31 '22 at 20:57
  • glad to hear it is working! I have updated the answer to include .Peek() as well – pthomson May 31 '22 at 21:33