如何避免 OnGet() 在 Asp.net 中将我的变量设置为 null

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

当 OnGetLendConfirm() 执行时,url 被设置为空,我不知道如何正确保存变量以便我可以在两个函数中使用它。

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

您将希望使用可用选项之一保留 url 字段的状态。 一些选项是

  • 临时数据
  • 隐藏表单域
  • 查询字符串
  • 路由数据
  • Cookies
  • 会话变量
  • 应用程序变量
  • 一种可用的缓存策略,例如 MemoryCache class

也许在您的示例中最容易实现的是将 url 设置为具有 getter 和 setter 的模型上的 TempData 字段,这应该使其可用于您随后的 LendConfirm Get 请求

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

TempData 值在您读取它们后立即过期,因此如果您想为多个后续请求保留该值,您可以像这样更新 LendConfirm:

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