Much
Much

Reputation: 165

How to get items for logged in user ASP.NET MVC

I am trying to show booking of logged in user from database, but its show all data from all user. this is the original code:

// GET: Bookings
public ActionResult Index()
{
   var bookings = db.Bookings.Include(b => b.Room).Include(b => b.Register);
   return View(bookings.ToList());
}

Here what I have tried but the output show an error,

public ActionResult Index()
{
   var bookings = db.Bookings.Include(b => b.Room).Include(b => b.Register == Session["id"]);
   return View(bookings.ToList());
}

This is the user table in the database, so if I login as user no.1, the booking data should display only customerID no.1, but the problem is, the data show all user bookings.

enter image description here

Here is the image of booking db, enter image description here

Here is the code for login:

[HttpPost]
public ActionResult Login(Register login)
{
    using (HotelBookingEntities db = new HotelBookingEntities())
    {
        var userDetails = db.Registers.Where(x => x.email == login.email && x.password == login.password).FirstOrDefault();

        if (userDetails == null)
        {
            ViewBag.WrongMessage = "Wrong username or password";
            return View("Login", login);
        }
        else
        {
           Session["id"] = userDetails.id;
           Session["username"] = userDetails.username;
           return RedirectToAction("Index", "Rooms");
        }
    }      
}

Upvotes: 2

Views: 567

Answers (1)

TanvirArjel
TanvirArjel

Reputation: 32069

Try as follows:

public ActionResult Index()
{
    int userId = Convert.ToInt32(Session["id"]);
    var bookings = db.Bookings.Where.Include(b => b.Room).Where(b => b.CustomerID == userId).ToList();

    return View(bookings);
}

Upvotes: 2

Related Questions