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

时间:2013-05-19 12:14:25

标签: asp.net-mvc model-view-controller controller

我想在控制器中保存一个变量,以便能够将它用于所有方法,所以我声明了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字符串,我该如何防止它发生?< / p>

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

3 个答案:

答案 0 :(得分: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)

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

答案 1 :(得分:1)

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

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

并且每当您想要使用该变量时,例如您想将其作为参数提供给方法,只需输入:

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

这就是在ASP.NET MVC中保存和使用变量的方法

答案 2 :(得分:0)

您可以在控制器中使用静态字段,以便在所有请求之间共享。

private static List<someObject> yourObjectList;

相关问题