是否可以在控制器中保存变量

rik*_*ket 0 model-view-controller asp.net-mvc controller

我想在控制器中保存一个变量,以便能够将它用于所有方法,所以我声明了3个私有字符串

public class BankAccountController : Controller
{
     private string dateF, dateT, accID;
    //controller methods
}
Run Code Online (Sandbox Code Playgroud)

现在这个方法改变了它们的值:

[HttpPost]
public ActionResult Filter(string dateFrom, string dateTo, string accountid)
{
     dateF = dateFrom;
     dateT = dateTo;
     accID = accountid;
     //rest of the code
}
Run Code Online (Sandbox Code Playgroud)

我使用了一个断点,当我调用那个控制器方法时变量正在被更改,但是当我调用其他控制器方法时,如下面的私有字符串被重置为emtpy字符串,我该如何防止它发生?

public ActionResult Print()
        {
            return new ActionAsPdf(
                "PrintFilter", new { dateFrom = dateF, dateTo = dateT, accountid = accID }) { FileName = "Account Transactions.pdf" };
        }

    public ActionResult PrintFilter(string dateFrom, string dateTo, string accountid)
    {
            CommonLayer.Account acc = BusinessLayer.AccountManager.Instance.getAccount(Convert.ToInt16(accID));
            ViewBag.Account = BusinessLayer.AccountManager.Instance.getAccount(Convert.ToInt16(accountid));
            ViewBag.SelectedAccount = Convert.ToInt16(accountid);
            List<CommonLayer.Transaction> trans = BusinessLayer.AccountManager.Instance.filter(Convert.ToDateTime(dateFrom), Convert.ToDateTime(dateTo), Convert.ToInt16(accountid));
            ViewBag.Transactions = trans;
            return View(BusinessLayer.AccountManager.Instance.getAccount(Convert.ToInt16(accountid)));
    }
Run Code Online (Sandbox Code Playgroud)

Ken*_*eth 7

将创建您创建控制器的新实例的每个请求,因此您的数据不会在请求之间共享.您可以执行以下操作来保存数据:

Session["dateF"] = new DateTime(); // save it in the session, (tied to user)
HttpContext.Application["dateF"] = new DateTime(); // save it in application (shared by all users)
Run Code Online (Sandbox Code Playgroud)

您可以以相同的方式检索值.当然,您也可以将其保存在其他地方,最重要的是,控制器实例不共享,您需要将其保存在其他地方.