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.
Here is the image of booking db,
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");
}
}
}
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);
}
Related
Hello I need help please
I am creating my first asp mvc Webpage.
I created a login and registration page connected with database.
I want to pass CustomerId from the customer that logged in to a Bookings table
So that it shows bookings related to that customer only.
Bookings table has CustomerId as a foreign key. This is what I have done so far.
public class BookingController : Controller
{
// GET: Booking
public ActionResult Index(int customerId)
{
TravelExpertsEntities bookingdb = new TravelExpertsEntities();
List<Booking> bookings = bookingdb.Bookings.Where(book =>
book.CustomerId == customerId).ToList();
return View(bookings);
}
}
}
//This is from login Controller
public ActionResult Login(Customer reg)
{
if (ModelState.IsValid)
{
var details = (from userlist in db.Customers
where userlist.UserName == reg.UserName &&
userlist.Password == reg.Password
select new
{
userlist.CustomerId,
userlist.UserName
}).ToList();
if (details.FirstOrDefault() != null)
{
Session["CustomerId"] =
details.FirstOrDefault().CustomerId;
Session["Username"] = details.FirstOrDefault().UserName;
return RedirectToAction("Index", "Booking");
}
}
else
{
ModelState.AddModelError("", "Invalid UserName or Password");
}
return View(reg);
}
I was able to pull all bookings but I want to filter it with the Customer that logged in.
Replace your RedirectToAction as below, to pass customerId as parameter
var CustomerIdparam=details.FirstOrDefault().CustomerId;
RedirectToAction("Index", "Booking", new{customerId=CustomerIdparam});
I have a ViewModel and Repository that are being used by the Controller Action for Create
Repository
BackendEntities entity = new BackendEntities();
public void AddCountry(CountriesViewModel countryModel)
{
COUNTRIES2 newCountry = new COUNTRIES2()
{
COUNTRY_ID = countryModel.COUNTRY_ID,
COUNTRY_CODE = countryModel.COUNTRY_CODE,
COUNTRY_NAME = countryModel.COUNTRY_NAME,
ACTION_STATUS = countryModel.ACTION_STATUS,
CREATED_BY = countryModel.CREATED_BY,
CREATED_DATE = countryModel.CREATED_DATE
};
entity.COUNTRIES.Add(newCountry);
entity.SaveChanges();
}
Then, I call the Repository from the Controller Action for Create.
Controller
public ActionResult Create(FormCollection collection, CountriesViewModel countries)
{
CountriesRepository countryRepo = new CountriesRepository();
if (ModelState.IsValid)
{
try
{
// TODO: Add update logic here
countryRepo.AddCountry(countries);
//countryRepo.
var notif = new UINotificationViewModel()
{
notif_message = "Record saved successfully",
notif_type = NotificationType.SUCCESS,
};
TempData["notif"] = notif;
return RedirectToAction("Index");
}
catch (Exception e)
{
this.AddNotification("Country cannot be added.<br/> Kindly verify the data.", NotificationType.ERROR);
}
}
return View(countries);
}
Please how do I Validate for duplicate COUNTRY_NAME using the condition, where ACTION_STATUS is not equal to 2
I don't want to do it from Model or View, but in the Controller or Repository.
Probably putting it before countryRepo.AddCountry(countries) in the Controller.
Create a Method In your Country Repository
public bool IsNameExist(string name, int id)
{
var result =entity.COUNTRIES.Any(c => c.COUNTRY_NAME == name && c.ACTION_STATUS != 2 && && c.COUNTRY_ID != id);
return result;
}
Then In your controller
public ActionResult Create(FormCollection collection, CountriesViewModel countries)
{
.......
if (countryRepo.IsNameExist(countries.COUNTRY_NAME, countries.COUNTRY_ID))
{
ModelState.AddModelError("COUNTRY_NAME", "COUNTRY NAME already exist.");
}
........
}
I have this table where displaying the list of userID+SubjectID, now i want is,if the user who Logged in can only see the list of Subject that belongs to the current user,is it possible? then should i need to use asp.net identity? currently i am using empty template with custom login Authentication + Roles only, any idea on what is the best way to handle this type of scenario? all i want is my tables will show data based on the current user logged in.
Example: If User1 logged in then User1 will only see subjects belong to user1..
Note:
i was searching for tutorials on showing data based on the current user logged in, but i couldn't find,any one has better idea? or link can share with me? i don't know the better word for my scenario i just call it "show data based on current user",i appreciate if anyone can solve this..thanks in advance..
Table Controller:
[CostumAuthorize(Roles = "Admin,Teacher")]
public ActionResult Subject_List(int id)
{
var test = db.SubjectTeachers.Where(x => x.Users.Any(n => n.UserID == id)).ToList();
var subjectTeachers = db.SubjectTeachers.Include(s => s.Levels).Include(s => s.Subjects).Include(s => s.Users).Where(u => u.LevelID == id);
return View(subjectTeachers.ToList());
}
Account controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(Login l, string ReturnUrl = "")
{
if (!ModelState.IsValid)
{
return View(l);
}
using (MyContext dc = new MyContext())
{
var user = dc.Users.Where(a => a.Username.Equals(l.Username) && a.Password.Equals(l.Password)).FirstOrDefault();
if (user != null)
{
FormsAuthentication.SetAuthCookie(user.Username, l.RememberMe);
if (Url.IsLocalUrl(ReturnUrl))
{
return Redirect(ReturnUrl);
}
return RedirectToAction("Index", "Home");
}
}
ModelState.AddModelError("", "Invalid Login.");
return View(l);
}
[Authorize]
public ActionResult Logout()
{
FormsAuthentication.SignOut();
return RedirectToAction("Login", "Account");
}
}
If you can get the logged-in userid then simply use that to get Corresponding Subjects list.........
int userid = Membership.GetUser(User.Identity.Name).ProviderUserKey;
[CostumAuthorize(Roles = "Admin,Teacher")]
public ActionResult Subject_List()
{
var test = db.SubjectTeachers.Where(x => x.Users.Any(n => n.UserID == userid )).ToList();
return View(test.ToList());
}
I have set the app to allow each user to have multiple roles.
public class SelectRoleViewModel
{
public string Id { get; set; }
public bool Checked { get; set; }
public string RoleName { get; set; }
public string Description { get; set; }
}
public class EditUser
{
// other properties
public List<SelectRoleViewModel> Roles { get; set; }
}
now in the Controlles, in the Edit get method I wrote this
[CustomAuthorize(Roles = ("Admin,Manager"))]
public ActionResult Edit(string Id)
{
var editUser = GetEditUser(Id);
bool isAdmin = User.IsInRole("Admin");
if (!isAdmin)
{
if (editUser.Roles.Exists(x => x.RoleName == "Admin"))
{
return RedirectToAction("AccessNotAllowed", "Errors");
}
}
// Here just edit what you want
return View(editUser);
}
private EditUser GetEditUser(string Id)
{
var dbUser = UserManager.Users.Where(x => x.Id == Id).FirstOrDefault();
var currentRoles = dbUser.Roles.Select(x => x.RoleId).ToList();
var allRoles = _roleManager.Roles.ToList();
EditUser editUser = new EditUser();
foreach (var x in allRoles)
{
if (currentRoles.Contains(x.Id))
editUser.Roles.Add(new SelectRoleViewModel { Id = x.Id, RoleName = x.Name, Description = x.Description, Checked = true });
else
editUser.Roles.Add(new SelectRoleViewModel { Id = x.Id, RoleName = x.Name, Description = x.Description, Checked = false });
}
if (User.IsInRole("Manager"))
{
// don't show the admin role to set for users if authenticated user is manager
var adm = editUser.Roles
.Where(x => x.RoleName.Equals("Admin", StringComparison.OrdinalIgnoreCase))
.FirstOrDefault();
if (adm != null)
{
editUser.Roles.Remove(adm);
}
}
editUser.FirstName = dbUser.FirstName;
editUser.LastName = dbUser.LastName;
editUser.Email = dbUser.Email;
editUser.UserName = dbUser.UserName;
editUser.Id = dbUser.Id;
return editUser;
}
So, the manager has the right to edit users and to create them, but manager can't create users with admin role.
What I'm trying to do is to deny access for the manager to edit the admin users.
The code I wrote, it takes the whole list of user roles, and since there is an admin role, it always denies access to edit users.
This happens when I comment out this code in the GetEditUser method:
if (User.IsInRole("Manager"))
{
// don't show the admin role to set for users if authenticated user is manager
var adm = editUser.Roles
.Where(x => x.RoleName.Equals("Admin", StringComparison.OrdinalIgnoreCase))
.FirstOrDefault();
if (adm != null)
{
editUser.Roles.Remove(adm);
}
}
and with this code (uncommented), it totally removes the admin role from the list, so the manager can still edit the admin users since it don't find the admin role to compare in the if condition.
Can someone help me find a solution to limit manager access for editing admin users and to hide the admin role for managers when creating new user, without changing the users to assign only 1 role? The logic of the app needs to have multiple roles per user.
Move the indicated section of code to the Edit method inside the if(!isAdmin):
if (!isAdmin)
{
if (editUser.Roles.Exists(x => x.RoleName == "Admin" && x.Checked))
{
return RedirectToAction("AccessNotAllowed", "Errors");
}
var adm = editUser.Roles
.Where(x => x.RoleName.Equals("Admin", StringComparison.OrdinalIgnoreCase))
.FirstOrDefault();
if (adm != null)
{
editUser.Roles.Remove(adm);
}
}
I'm following this tutorial link
I have a table users {iduser, user, pass, role}
I'm using this users : string[] users = db.users.Select(t => t.user).ToArray();
instead of : string[] users = Users.Split(','); Is it ok ?
My problem is with roles : SiteRoles role = (SiteRoles)httpContext.Session["role"];
Q: Where do I store the role for my user ?
My simplified account controller:
[HttpPost]
public ActionResult Login(LoginModel model)
{
HeliosEntities db = new HeliosEntities();
if (ModelState.IsValid)
{
bool userok = db.users.Any(t => t.user == model.UserName && t.pass == model.Password);
if (userok == true)
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
return RedirectToAction("Index", "Home");
}
{
ModelState.AddModelError("", "Incorect password or user!");
}
}
return View();
}
A quick look at your link above shows that it is getting the user's role from session:
(SiteRoles)httpContext.Session["role"];
so you need to set the session value when the user logs in, for example:
var userRole = Roles.Admin | Roles.User;
httpContext.Session["role"] = role;
I don't know where you store the information about what role the user is in though.