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

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...