Home > Enterprise >  How to avoid OnGet() setting my variables to null in Asp.net
How to avoid OnGet() setting my variables to null in Asp.net

Time:06-01

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);
    }
}

CodePudding user response:

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);
}
  • Related