【发布时间】:2019-03-07 13:12:22
【问题描述】:
我正在使用 ASP.net mvc 制作一个 Web 应用程序。您可以在以下位置查看食谱:/recipe
问题是当我在 /recipe/create 添加食谱时,它不起作用。我希望它显示在 /recipe 页面上。 Recipe Page
所以我认为控制器或视图有问题,但我认为是控制器。
这里是 recipeController 的代码:
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>
<div class="form-group">
<label asp-for="Category">Categorie</label>
<select class="form-control" asp-for="Category">
<option value="0">none</option>
<option value="0">Cake</option>
<option value="0">Desert</option>
<option value="0">Sidedish</option>
<option value="0">Maincourse</option>
</select>
</div>
<div class="form-group">
<label asp-for="NumberOfIngredients">Aantal</label>
<input asp-for="NumberOfIngredients" type="number" class="form-control" name="number" />
</div>
<button type="submit" class="btn btn-primary">Voeg toe</button>
</form>
</div>
因此,当我添加食谱时,它会返回到食谱页面,但不会显示添加的食谱。我做错了什么? Create Recipe Page
【问题讨论】:
-
可能与您的问题没有任何关系,但是您的所有类别
options 都具有value="0"是故意的吗? -
您确定它甚至将其添加到控制器中的列表中吗?尝试添加一个然后添加另一个,但在添加第二个之前在控制器上放置一个断点。查看第一个是否已添加
-
@Rafalon 我忘记改了:),
-
@JamesS 是的,它确实添加到列表中,但索引页面对它没有任何作用
-
@TheProgrammer 我可能会看看下面 HenkHoterman 的回答。问题可能是因为它不是静态列表,因此每次调用控制器时都会重置
标签: c# asp.net-mvc forms model controller