2013-05-19 129 views
0

我想保存的变量在控制器中能够使用它的所有方法,所以我宣布3个私人字符串是否有可能挽救一个变量在控制器

public class BankAccountController : Controller 
{ 
    private string dateF, dateT, accID; 
    //controller methods 
} 

现在这种方法更改它们的值:

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

我用了一个断点,当我调用控制器的方法,但是当我调用其他控制器的方法,如这些民营串下方正在重置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))); 
    } 

回答

6

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

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) 

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

1

以下方法非常简单,并确保变量与当前用户绑定,而不是在整个应用程序中使用它。所有你需要做的就是在控制器上键入以下代码:

Session["dateF"] = dateFrom; 
Session["dateT"] = dateTo; 
Session["accID"] = accountid; 

,只要你想使用这个变量,比如你想给它作为一个参数的方法,你只需要输入这个:

MyMethod(Session["dateF"].ToString()); 

这就是你如何在ASP.NET MVC中保存和使用一个变量

相关问题