[英]Routing issue after changing primary keys
將主鍵從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
起作用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?}");
});
您的動作參數名為id
。 當您將點與命名參數一起使用時,例如https://localhost:xxxxx/Posts/Details?PostId=4
MVC會嘗試將PostId
序列化為具有相同名稱的參數。 您可以重命名參數或使用前綴。
Task<IActionResult> Details([Bind(Prefix="PostId")] int? id)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.