locked
How to retrieve database data on selected attribute with foreach loop? RRS feed

  • Question

  • User-578960655 posted

    Hi, i want to know how to listed/retrieve data from selected database table with foreach loop, but without showing ALL data instead i want to show selected data only. 

    Example on html syntax, call it MenuList.cshtml

           @foreach (var item in Model.Menu)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.Breakfast)
                    </td>

    DbController.cs

            public static List<Menu> LoadMenu()
            {
                string sql = @"select MenuID, Breakfast from dbo.Menu;";
    
                return SqlDataAccess.LoadData<Menu>(sql);
            }

    MenuList.cshtml.cs

            public ActionResult ViewMenu()
            {
                ViewBag.Message = "Menu List";
    
                var data = LoadMenu();
                List<Menu> menu = new List<Menu>();
    
                foreach(var row in data)
                {
                    menu.Add(new Menu
                    {
                        Breakfast = row.Breakfast
                    });
                }
                return Page();
            }

    In Menu.cs, i provided 3 data in Breakfast attribute. I would like to show only 1 from 3 data. How should i limit the foreach loop?

    Saturday, May 30, 2020 6:40 AM

All replies

  • User303363814 posted

    Change your sql so it only retrieves the rows that you want.

    select MenuID, Breakfast from dbo.Menu where ….

    Monday, June 1, 2020 12:43 AM
  • User-2054057000 posted

    You could use a LINQ query with Where condition after this something like:

    SqlDataAccess.LoadData<Menu>(sql).Where(t => t.Name =="Jack");

    Monday, June 1, 2020 6:02 AM
  • User1686398519 posted

    Hi,  emirryhn

    You can use "if" in your loop to judge based on a certain condition.

    data.ForEach(m =>
    {
         if (m.MenuID == 1)
         {
              menu.Add(new Menu { Breakfast = m.Breakfast });
         }
    });

    OR

    foreach (var row in data)
                {
                    if (row.MenuID == 1)
                    {
                        menu.Add(new Menu
                        {
                            Breakfast = row.Breakfast
                        });
                 }
    }

    Here is the result.

     
    Best Regards,

    YihuiSun

    Monday, June 1, 2020 8:35 AM