我正在用 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>因此,当我添加食谱时,它会返回到食谱页面,但不会显示添加的食谱。我做错了什么?创建食谱页面
1 回答

一只甜甜圈
TA贡献1836条经验 获得超5个赞
public class RecipeController : Controller{ List<RecipeViewModel> vm = new List<RecipeViewModel>();
您的vm
列表是一个实例字段。控制器和列表将在每次请求时再次创建。
对于一个简单的(演示)解决方案,将其设为静态:
static List<RecipeViewModel> vm = new List<RecipeViewModel>();
这不是线程安全的,也不适合生产。但是你应该能够试驾它。
- 1 回答
- 0 关注
- 107 浏览
添加回答
举报
0/150
提交
取消