我读了《 ASP.NET MVC的Pro Entity Framework Core 2》一书。我目前在第12章的开头,遇到了一些问题。我有这个控制器:
namespace DataApp.Controllers
{
public class HomeController : Controller
{
private IDataRepository repository;
public HomeController(IDataRepository repo)
{
repository = repo;
}
public IActionResult Index()
{
return View(repository.GetAllProducts());
}
public IActionResult Create()
{
ViewBag.CreateMode = true;
return View("Editor", new Product());
}
[HttpPost]
public IActionResult Create(Product product)
{
repository.CreateProduct(product);
return RedirectToAction(nameof(Index));
}
public IActionResult Edit(long id)
{
ViewBag.CreateMode = false;
return View("Editor", repository.GetProduct(id));
}
[HttpPost]
public IActionResult Edit(Product product)
{
repository.UpdateProduct(product);
return RedirectToAction(nameof(Index));
}
[HttpPost]
public IActionResult Delete(long id)
{
repository.DeleteProduct(id);
return RedirectToAction(nameof(Index));
}
}
}
索引视图如下:
@model IEnumerable<DataApp.Models.Product>
@{
ViewData["Title"] = "Products";
Layout = "_Layout";
}
<table class="table table-sm table-striped">
<thead>
<tr><th>ID</th><th>Name</th><th>Category</th><th>Price</th></tr>
</thead>
<tbody>
@foreach (var p in Model)
{
<tr>
<td>@p.Id</td>
<td>@p.Name</td>
<td>@p.Category</td>
<td>$@p.Price.ToString("F2")</td>
<td>
<form asp-action="Delete" method="post">
<a asp-action="Edit"
class="btn btn-sm btn-warning" asp-route-id="@p.Id">
Edit
</a>
<input type="hidden" name="id" value="@p.Id" />
<button type="submit" class="btn btn-danger btn-sm">
Delete
</button>
</form>
</td>
</tr>
}
</tbody>
</table>
<a asp-action="Create" class="btn btn-primary">Create New Product</a>
如果我运行该应用程序并单击“编辑”或“创建”按钮,则不会显示“编辑器”视图。如果我在浏览器中导航到/ Home / Edit,则显示该视图。可能是什么问题?
您可以在此处找到本章的完整源代码:
请注意,我位于本章的开头,源代码中的文件可能包含我目前拥有的更多文件,但根据该书,它也应在此阶段工作。