Basiyath T Zubair
Basiyath T Zubair

Reputation: 39

How to deal with a non existing session variable?

I am trying to check if a booking record exists, then show its details. Otherwise return to Bookparking page but else part isn't working and shows Object reference not set to an instance of an object because there is no such field with the Session[""]

Controller:

public ActionResult Viewparking()
{
   if (IsUserLoggedIn(Session, Request) == false)
   {
       return RedirectToAction("login");
   }
   else
   {
       String id = Session["username"].ToString();
       ViewBag.userid = id;
       var checkbooking = db.tb_booking.Where(s => s.username == id).FirstOrDefault();
       if (checkbooking != null)
       {
           var show = db.tb_booking.Where(e => e.username == id).FirstOrDefault();
       }
       else
       {   //ViewBag.f = "You have no booking yet!!";
           return RedirectToAction("Bookparking", "user");
       }
       return View();
   }
}

Upvotes: 0

Views: 47

Answers (1)

RoelA
RoelA

Reputation: 601

As Gabriel noted, you have not null checked the value from the session. Code would be something like this:

public ActionResult Viewparking()
{
    if (IsUserLoggedIn(Session, Request) == false)
    {
        return RedirectToAction("login");
    }
    else
    {
        String id = Session["username"]?.ToString();
        if (id != null)
        {
            ViewBag.userid = id;
            var checkbooking = db.tb_booking.FirstOrDefault(s => s.username == id);
            if (checkbooking != null)
            {   // TODO: checkbooking is currently unused, except to check if you can fetch it.
                return View();
            }
        }
        // If you reach this code, then either id is null, or the booking was not found
        return RedirectToAction("Bookparking", "user");
    }
}

Upvotes: 1

Related Questions