How can we check whether the Session["KEY"] is previously Created or Not in ASP.Net MVC

Viewed 34

How can we check whether the Session["KEY"] is previously Created or Not, instead of just checking the following:

if(Session["KEY"] == null)

Depending on the Session["KEY"] value, I am deciding whether to add a record to database of update the record by using identified contained in Session["KEY"]. Sample code given below.

if(Session["ID"] == null)
    //Insert a record in database
else
   //Update record in database by id
   string id =  Session["ID"]

The above code is on my DataEntry page which perform both the insert and update.

I have a another page say Login page where existing user login by his id and then he goes to DataEntry page to submit his update. On login page, I save his id in session to use this while loading user data on DataEntry page and also update his data using the id contained in session. I store the id in session on Login page as follows:

Session["ID"] = "123";//Actual id entered by the user.

Login page and loading the data on DataEntry page is fine. Also the new data entry from DataEntry page (This is without the Login page) is works fine. Only problem with the update operation when the session is expired because application is trying to insert the record instead of update.

So in this scenario, is it possible to check that whether we have created Session["ID"] previously or not? Because the "Session["ID"] == null" is exists in both the case of insert and update.

If we know that we have created the Session["ID"] previously and now it is expired on DataEntry page then we assure that its a update case and we skip the insert and may be we redirect user again to login page. Vice a versa, If we know that we have NOT created the Session["ID"] and it is null on DataEntry page then we will go with Insert and will skip the Update.

As I newer to web application, any help/suggestions will be highly appreciated.

0 Answers
Related