Hello
I’ve just created a simple MVC 5 application (CRUD) from a 3 table database. When I start the application I go to the Index page that lists all data from the main table. In the main table I have a field that holds user login id’s (network login’s). I
would like to filter the data shown based on the user that is currently logged in. Can someone please help me understand how I do this (or point me in the right direction)?
Many thanks,
Andy
In the controller action that retrieves data add a where. What is the code that adds retrieves
AndyMcV
ll data from the main table.
?
If you are using MVC, you should be pulling all of the values that you are displaying and passing them to your View within the Controller.
For instance, if you have some code that looks like the following to grab all of your Widget objects and pass them to the View :
public ActionResult DisplayWidgets() { // Example context using Entity Framework using(var context = new WidgetContext()) { // Grab your widgets var widgets = context.Widgets.ToList(); // Pass your collection of widgets to your View return View("YourViewName",widgets); } }
And you wanted to apply a specific filter using a WHERE clause to this, you would just need to add a bit of LINQ as seen below :
public ActionResult DisplayWidgets() { // Example context using Entity Framework using(var context = new WidgetContext()) { // Get your current user (example) var username = User.Identity.Name; // Grab your widgets that belong to this user var widgets = context.Widgets.Where(w => w.WidgetOwner = username) .ToList(); // Pass your collection of widgets to your View return View("YourViewName",widgets); } }
This is obviously just an example and your implementation may vary, but it should help demonstrating the most basic way to apply filtering using WHERE clauses.
Hi Rion
This is the code that was created when I created my controller. I’m not 100% sure where to add the where clause here.
Namespace HSTracker Public Class HSTrackerController Inherits System.Web.Mvc.Controller Private db As New EHSTrackerEntities ' GET: /HSTracker/ Function Index() As ActionResult Dim employeeactions = db.EmployeeActions.Include(Function(e) e.Action).Include(Function(e) e.Manager) Return View(employeeactions.ToList()) End Function
... and so on...
The index page (view) looks like this.
You could add it as a method similar to your Include() method :
Function Index() As ActionResult ' Get your Employee Actions where the Description is not the empty string ' Dim employeeactions = db.EmployeeActions.Include(Function(e) e.Action).Include(Function(e) e.Manager).Where(Function(a) a.Description != "") ' Pass your actions to the View ' Return View(employeeactions.ToList()) End Function
This is just an example of some type of logic that you could include. Does that make things any clearer?
Perfect!! I changed the != to <> and it worked great.
Thanks Rion!!