Группировка списка значений из модели mvc в таблицу html - PullRequest
0 голосов
/ 26 октября 2018

Я столкнулся с проблемой работы с проектом asp .net mvc.

У меня есть страница генератора рецептов, которая отображает названия рецептов, ингредиенты и инструкции в таблице с использованием HTML.

Я извлекаю информацию о рецептах из своей базы данных, и в моей базе данных каждый рецепт содержит несколько ингредиентов, которые идут вместе с ним.

Задача для меня - получить название рецепта, соответствующие ингредиенты и инструкции в одной строке таблицы html. Проблема, которую я пытался обойти, состоит в том, что она будет отображать несколько строк для одного и того же рецепта, потому что ингредиенты перечислены несколько раз, поэтому я попытался сделать так, чтобы к модели был добавлен список ингредиентов для каждого рецепта, но не работает очень хорошо.

Я покажу свой код для Модели, Представления и Контроллера, которые у меня сейчас есть, в надежде, что кто-то сможет настроить мои методы и указать мне правильное направление.

Модель:

using System;
using System.Collections.Generic;
using System.Web.Mvc;

namespace MyPantry.Models
{
    public class Recipes
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public List<string> IngredientName { get; set; }
        public string Instructions { get; set; }
    }

}

Просмотр:

<h1 class="m-b-20" style="font-size: 4vw; margin-top: 10px; margin-left: 37%; margin-right: 41.5%; border-style: solid">My Recipes</h1>

<form method="post">
    <div>
        @model List<Recipes>

        <table class="table table-bordered table-responsive table- hover">
            <tr>
                <th>Name</th>
                <th>Ingredients</th>
                <th>Instructions</th>
            </tr>

            @foreach (var recipe in Model)
            {
                <tr>
                    <td>@recipe.Name</td>
                    <td>@Html.DisplayFor(model => recipe.IngredientName)</td>
                    <td>@recipe.Instructions</td>
                </tr>
            }
        </table>
    </div>
</form>

Контроллер:

       public IActionResult RecipeList()
    {
        var ls = new List<Recipes>();

        SqlConnection connection = GetConnection();

        try
        {
            using (connection)
            {
                connection.Open();
                StringBuilder sb = new StringBuilder();
                sb.Append("SELECT ingredients.name as IngName, recipes.name, recipes.instructions ");
                sb.Append("FROM recipes, recipe_ingredients, ingredients ");
                sb.Append("WHERE recipes.id = recipe_ingredients.recipe_id and recipe_ingredients.Ingredient_id = ingredients.id;");
                String sql = sb.ToString();

                using (SqlCommand command = new SqlCommand(sql, connection))
                {
                    using (SqlDataReader rdr = command.ExecuteReader())
                    {
                        while (rdr.Read())
                        {
                            var recipe = new Recipes();
                            recipe.Name = rdr["name"].ToString();
                            recipe.Instructions = rdr["instructions"].ToString();
                            recipe.IngredientName.Add(Convert.ToString(rdr["IngName"]));

                            ls.Add(recipe);
                        }
                    }
                }
            }
        }

        catch (SqlException e)
        {
            Console.WriteLine(e.ToString());
        }

        return View(ls);

    }

Ответы [ 2 ]

0 голосов
/ 31 октября 2018

Обновление ... Я нашел решение, которое работает для моей таблицы.

Контроллер:

      public IActionResult RecipeList()
    {
        var ls = new List<Recipes>();

        SqlConnection connection = GetConnection();

        try
        {
            using (connection)
            {
                connection.Open();
                SqlCommand cmd = new SqlCommand("select distinct recipes.name, recipes.instructions from recipes;");
                cmd.Connection = connection;

                DataSet ds = new DataSet();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                connection.Close();

                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    var recipe = new Recipes();
                    recipe.Name = Convert.ToString(dr["name"]);
                    recipe.IngredientName = RecipeIngredientsList(recipe.Name);
                    recipe.Instructions = Convert.ToString(dr["instructions"]);
                    ls.Add(recipe);
                }

            }
        }

        catch (SqlException e)
        {
            Console.WriteLine(e.ToString());
        }

        return View(ls);

    }

    public List<string> RecipeIngredientsList(string Name)
    {
        List<string> ingredients = new List<string>();

        SqlConnection connection = GetConnection();

        try
        {
           using (connection)
            {
                connection.Open();
                SqlCommand cmd = new SqlCommand("select ingredients.name " +
                                                "from ingredients, recipe_ingredients, recipes " +
                                                "where recipes.id = recipe_ingredients.recipe_id and recipe_ingredients.ingredient_id = ingredients.id and recipes.name = @Name;");
                cmd.Parameters.AddWithValue("@Name", Name);
                cmd.Connection = connection;

                DataSet ds = new DataSet();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                connection.Close();

                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    ingredients.Add(Convert.ToString(dr["name"]) + "\n");
                }
            }
        }

        catch (SqlException e)
        {
            Console.WriteLine(e.ToString());
        }

        return ingredients;

    }

Вид:

   <h1 class="m-b-20" style="font-size: 4vw; margin-top: 10px; margin-left: 37%; margin-right: 38%; border-style: solid">My Recipes</h1>

<form method="post">
    <div>
        @model List<Recipes>

        <table class="table table-bordered table-responsive table-hover">
            <tr>
                <th>Name</th>
                <th>Ingredients</th>
                <th>Instructions</th>
            </tr>

            @foreach (var recipe in Model)
            {
            <tr>
                <td>@recipe.Name</td>
                <td>@Html.DisplayFor(m => recipe.IngredientName)</td>
                <td>@recipe.Instructions</td>
            </tr>
            }
        </table>
    </div>
</form>

Модель:

namespace MyPantry.Models
{
    public class Recipes
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public List<string> IngredientName { get; set; }
        public string Instructions { get; set; }
    }
}

Результат изображения

0 голосов
/ 26 октября 2018

Я согласен с тем, что говорит Джек, но вы также можете захотеть посмотреть на соединения с вашими SQL-скриптами, а также использовать Distinct, чтобы избежать получения ваших кратных данных ингредиентов. Вы можете использовать для этого вложенный запрос.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...