2017-01-31 28 views
1

在ASP.NET MVC中,一個在方法外部聲明的字段,該字段每次都會初始化。如何爲MVC Controller中的每個客戶端初始化一次字段?

那裏我給出了一個演示例子。

public class TestController : Controller 
{ 

    private List<object> ListItems; 
    // GET: /Test/Index 
    public ActionResult Index(int Id) 
    { 
     ModelSource _model = new ModelSource(Id); 
     ListItems = _model.GetItems();//coming info from Model 
     return View(); 
    } 


    // GET: /Test/Demo 
    public ActionResult Demo() 
    { 
     int x = ListItems.Count; 
     //Do Something More 
     return View(x); 
    } 
} 

有可能是ListItems將初始化一次爲每個客戶端作爲Id參數將會對客戶的要求不同。

+1

保存在'Session'中。 –

+0

@PatrickHofman,首先,謝謝你的回覆,你能給我一些參考嗎? –

+1

http://stackoverflow.com/q/14138872/993547 –

回答

2

正如帕特里克·霍夫曼說,你可以使用SessionsCookies下面是兩個例子:

餅乾:

string cookievalue ; 
if (Request.Cookies["cookie"] != null) 
{ 
    cookievalue = Request.Cookies["cookie"].ToString(); 
} 
else 
{ 
    Response.Cookies["cookie"].Value = "cookie value"; 
} 
//For removing cookie use following code 

if (Request.Cookies["cookie"] != null) 
{ 
    Response.Cookies["cookie"].Expires = DateTime.Now.AddDays(-1); 
} 

會議:

HttpContext.Current.Session.Add("Title", "Data"); 

string foo = Session["Title"]; 
+0

是的!我試過了。它的作品:) –

+0

@RitwickDey很高興它做了=) – Valkyrie

相關問題