0

Morning folks,

Im using c# within my mvc project. i have an index view that lists household members.

This works fine and pulls back the all of the records in the database.

 public ActionResult Index()
    {
        List<Household> houseRecords = db.Households.ToList();

        return View(houseRecords);
    }

I have created another list view page named ListMembers(), This list is based on family members and so i want this view to pull back records specific to the referral i have created (ClientId).

I have thought that i might be able to add a where clause to my List code and base this on the ClientId but im not 100% sure this will work.

 List<Household> houseRecords = db.Households.ToList().Where(x => x.ClientId = x.id);

Can anyone point me in the right direction?

Regards Betty

Betty Lazzari
  • 99
  • 1
  • 6
  • 13

3 Answers3

0

Assuming you want to filter your list based on an id passed in via URL, you can add a parameter to your action method and use this to filter.

Note that from your example in the question, you should be performing the filter logic on the IQueryable rather than after calling ToList() to prevent all records being loaded into memory.

// <root>/<controller>/ListMembers/123 (using default route)
public ActionResult ListMembers(int clientId)
{
    var houseRecords = db.Households.Where(x => x.ClientId == clientId).ToList();
    return View(houseRecords);
}
Chris Pickford
  • 8,642
  • 5
  • 42
  • 73
0

it will work as i believe but you can do it this way

 var  houseRecords = db.Households.Where(x => x.ClientId = x.id).ToList(); 

i think it more better to do the where before get the final list

moath naji
  • 663
  • 1
  • 4
  • 20
0

I am not sure why you say that "you dont think it will work"? the problems that i can see in what you have mentioned are
1. List<Household> houseRecords = db.Households.ToList().Where(x => x.ClientId = x.id); should be changed to

List<Household> houseRecords = db.Households.Where(x => x.ClientId = x.id).ToList();

Notice the .ToList at the end

  1. Since you are creating an action method by the name of

    ListMembers()

you should some how create an action method that accepts the client id and then uses it in the query. So Something like this public ActionResult ListMembers(int clientId) { var houseRecords = db.Households.Where(x => x.ClientId = clientId).ToList(); return View(houseRecords); } and then depending on your routes you can call the method like this

http://<BaseUrl>/ListMembers?clientId=123
Parv Sharma
  • 12,581
  • 4
  • 48
  • 80