【发布时间】:2019-11-23 04:12:15
【问题描述】:
将主键从ID 更改为PostId 后,Post Details.cshtml 视图似乎无法正确呈现 URL。
如果我导航到https://localhost:xxxxx/Posts/Details/4,页面将正确呈现。但是,以前工作的 Index.cshtml 视图中的 @Html.ActionLink 调用现在不再工作。它指向https://localhost:xxxxx/Posts/Details?PostId=4,这是一个空白页。不过,该 URL 似乎应该可以工作,所以我不确定路由是问题还是与视图有关。一个单独的类(也改变了它的主键)也发生了同样的问题。
Index.cshtml 视图中的<a asp-action="Details" asp-route-id="@item.PostId">Details</a> 链接确实通过指向https://localhost:xxxxx/Posts/Details/4 起作用。
Index.cshtml
@model IEnumerable<Website.Models.Post>
<table class="table">
<thead>
<tr>
<th>
<a asp-action="Index" asp-route-sortOrder="@ViewData["TitleSortParm"]">@Html.DisplayNameFor(model => model.Title)</a>
</th>
<th>
<a asp-action="Index" asp-route-sortOrder="@ViewData["AuthorSortParm"]">@Html.DisplayNameFor(model => model.Author.LastName)</a>
</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.ActionLink(item.Title, "Details", "Posts", new { item.PostId })
</td>
<td>
@Html.ActionLink(item.Author.FullName, "Details", "Authors", new { item.Author.AuthorId })
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.PostId">Edit</a> |
<a asp-action="Details" asp-route-id="@item.PostId">Details</a> |
<a asp-action="Delete" asp-route-id="@item.PostId">Delete</a>
</td>
</tr>
}
</tbody>
</table>
PostsController.cs(仅相关Details get 方法)
namespace Website.Controllers
{
public class PostsController : Controller
{
private readonly Website.Data.ApplicationDbContext _context;
public PostsController(Website.Data.ApplicationDbContext context)
{
_context = context;
}
// GET: Post/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var post = await _context.Post
.Include(p => p.Author)
.FirstOrDefaultAsync(m => m.PostId == id);
if (post == null)
{
return NotFound();
}
return View(post);
}
}
}
Post.cs
namespace Website.Models
{
public class Post // dependent on Author
{
public int PostId { get; set; } // primary key
public string Title { get; set; }
public string Description { get; set; }
public DateTime PublicationDate { get; set; }
public int AuthorId { get; set; } // author foreign key
public Author Author { get; set; } // author navigation property
public ICollection<Tag> Tags { get; set; }
}
}
在 Startup.cs 中,路由信息(从未更改过,只是默认):
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
【问题讨论】:
标签: c# asp.net asp.net-mvc asp.net-core routing