Reputation: 469
I have a StudentController page which I want to display only the information of the User who is currently logged in. Like right now when a student logs in to his account, he is able to see the list of all the students in the University.
I want to restrict the view to only his account. I am trying to work with the Index method in the Controller, but I am experiencing issues with the PagedList View when I try to get students by User.Identity.GetUserId() select s;
instead of studentRepository.GetStudents()
.
// GET: /Student/
public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page)
{
ViewBag.CurrentSort = sortOrder;
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";
if (searchString != null)
{
page = 1;
}
else
{
searchString = currentFilter;
}
ViewBag.CurrentFilter = searchString;
//var students = from s in User.Identity.GetUserId() select s;
var students = from s in studentRepository.GetStudents()
select s;
if (!String.IsNullOrEmpty(searchString))
{
students = students.Where(s => s.LastName.ToUpper().Contains(searchString.ToUpper())
|| s.FirstMidName.ToUpper().Contains(searchString.ToUpper()));
}
switch (sortOrder)
{
case "name_desc":
students = students.OrderByDescending(s => s.LastName);
break;
case "Date":
students = students.OrderBy(s => s.EnrollmentDate);
break;
case "date_desc":
students = students.OrderByDescending(s => s.EnrollmentDate);
break;
default: // Name ascending
students = students.OrderBy(s => s.LastName);
break;
}
int pageSize = 3;
int pageNumber = (page ?? 1);
return View(students.ToPagedList(pageNumber, pageSize));
}
//
// GET: /Student/Details/5
public ViewResult Details(int id)
{
Student student = studentRepository.GetStudentByID(id);
return View(student);
}
Upvotes: 1
Views: 986
Reputation: 62488
You can put a where clause in your linq query there to display only that student's information :
var loggedInStudentId = User.Identity.GetUserId();
from s in studentRepository.GetStudents()
where s.StudentId == loggedInStudentId
select s
you can check if user is not admin then show only his own record like:
var students = from s in studentRepository.GetStudents()
select s;
if(!User.IsInRole("Admin"))
{
var loggedInStudentId = User.Identity.GetUserId();
students = students.Where(x=>x.StudentId = loggedInStudentId);
}
Upvotes: 2
Reputation: 8926
Try something like this:
var students = from s in studentRepository.GetStudents()
where s.Id = User.Identity.GetUserId()
select s;
you'll have to use whatever identity column you're using on student that would match up with GetUserId(), I put s.Id in here for example
Upvotes: 0