ASP dot net mvc - 将项目添加到列表不起作用,它什么也不做

我正在用 ASP.net mvc 制作一个 web 应用程序。您可以在以下位置查看食谱:/recipe


问题是当我在 /recipe/create 添加食谱时,它不起作用。我希望它显示在 /recipe 页面上。食谱页面


所以我认为控制器或视图有问题,但我认为是控制器。


这是配方控制器代码:


 public class RecipeController : Controller

{

    List<RecipeViewModel> vm = new List<RecipeViewModel>();


    public IActionResult Index()

    {

        foreach (var recept in MockDataRecipeFactory.GetRecipes())

        {

            vm.Add(new RecipeViewModel

            {

                Id = recept.Id,

                Name = recept.Name,

                Category = recept.Category,

                NumberOfIngredients = recept.Ingredients.Count

            });

        }

        return View(vm);

    }


    public IActionResult Create()

    {

        return View();

    }


    [HttpPost]

    public IActionResult Create(RecipeViewModel recipemodel)

    {

        vm.Add(new RecipeViewModel

        {

            Name = recipemodel.Name,

            Id = recipemodel.Id,

            Category = recipemodel.Category,

            NumberOfIngredients = recipemodel.NumberOfIngredients

        });


        return RedirectToAction("Index");

    }

我所做的是,我在顶部有一个 RecipeViewModel 列表,并将创建的项目添加到该列表中。


这是 RecipeViewModel :


    public class RecipeViewModel

{

    public int Id { get; set; }

    [DisplayName("Naam")]

    public string Name { get; set; }

    [DisplayName("Categorie")]

    public RecipeCategory Category { get; set; }

    [DisplayName("Aantal")]

    public int NumberOfIngredients { get; set; }

}

这是视图中的表单:


<div class="row">

<div class="col-md-4">

    <form asp-action="Create">

        <div class="form-group">

            <label asp-for="Id">Id:</label>

            <input asp-for="Id" type="text" class="form-control" name="id" />

        </div>

        <div class="form-group">

            <label asp-for="Name">Naam:</label>

            <input asp-for="Name" type="text" class="form-control" name="name" />

        </div>



因此,当我添加食谱时,它会返回到食谱页面,但不会显示添加的食谱。我做错了什么?创建食谱页面


慕工程0101907
浏览 117回答 1
1回答

一只甜甜圈

public&nbsp;class&nbsp;RecipeController&nbsp;:&nbsp;Controller{ &nbsp;&nbsp;&nbsp;&nbsp;List<RecipeViewModel>&nbsp;vm&nbsp;=&nbsp;new&nbsp;List<RecipeViewModel>();您的vm列表是一个实例字段。控制器和列表将在每次请求时再次创建。对于一个简单的(演示)解决方案,将其设为静态:static&nbsp;List<RecipeViewModel>&nbsp;vm&nbsp;=&nbsp;new&nbsp;List<RecipeViewModel>();这不是线程安全的,也不适合生产。但是你应该能够试驾它。
打开App,查看更多内容
随时随地看视频慕课网APP