Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
559 views
in Technique[技术] by (71.8m points)

asp.net mvc keep object alive, information

i have this code

[HttpPost]
public ActionResult Index(LoginModel loginModel)
{
    if (ModelState.IsValid)
    { 
       // some lines of code . bla bla bla
       TempData["loginModel"] = loginModel;
       return RedirectToAction("index", "premium");
     }
     ...
}

and this controller here

public ActionResult Index()
{
   var loginModel = TempData["loginModel"] as LoginModel;
   ...
}

now, when the page loads, everything seems to work fine. but when i refresh, everything messes up, it says that the loginModel is like null. the question is, how can i like keep track of the current login users. i have forms authentication enabled. tnx

error is as below


Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web     request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error: 


Line 22: 
Line 23:             var loginModel = TempData["loginModel"] as LoginModel;
Line 24:             string username = loginModel.username;
Line 25:             string password = loginModel.password;
Line 26:             premiumModel.username = username;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Confusion

but when i refresh, everything messes up, it says that the loginModel is like null

Answer

This is due to the fact that you have read the TempData key and Once it is read, data will be lost for that particular key.

var Value = TempData["keyName"] //Once read, data will be lost

Question

how can i like keep track of the current login users

Answer

So to persist the data even after the data is read you can Alive it like below

var Value = TempData["keyName"];
TempData.Keep();                 //Data will not be lost for all Keys
TempData.Keep("keyName");        //Data will not be lost for this Key

TempData works in new Tabs/Windows also, like Session variable does.

You could use Session Variable also, Only major problem is that Session Variable are very heavy comparing with TempData. Finally you are able to keep the data across Controllers/Area also.

Hope this post will help you alot.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...