2013-05-19 43 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中保存和使用一個變量

相關問題