亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

C#
慕工程0101907 2022-10-15 14:45:40
我正在用 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列表是一個實例字段??刂破骱土斜韺⒃诿看握埱髸r再次創建。

對于一個簡單的(演示)解決方案,將其設為靜態:

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

這不是線程安全的,也不適合生產。但是你應該能夠試駕它。


查看完整回答
反對 回復 2022-10-15
  • 1 回答
  • 0 關注
  • 91 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號