当通过slug而不是Id访问详细信息时,从另一个控制器访问详细信息视图



我有两个模型发布和注释

public class Post
{
[Key]
public Guid Id { get; set; }
public string Slug { get; set; }
public class Comment
{
public Guid Id { get; set; }
public Guid PostId { get; set; }
public virtual Post Post { get; set; }
....
}

这些评论是在帖子详细信息页面中创建的,我在那里将postId隐藏起来。这些帖子是通过在帖子创建过程中创建的slug访问的。

帖子提交后,用户应该返回到帖子页面。注释是通过注释控制器中的create()操作方法创建的。如果是通过Id,我可以进行

return RedirectToAction("Details","Posts" , new { id = postId });

但是由于slug而不是id,当使用slug访问帖子详细信息而不是id时我该怎么办。我确实试过把鼻涕虫藏在视野里这是在评论控制器中创建的评论

public async Task<IActionResult> Create([Bind("PostId,Body")] Comment comment)
{
if (ModelState.IsValid)
{
comment.Created = DateTime.Now;
comment.Id = Guid.NewGuid();

_context.Add(comment);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));

}

这是视图这里Post.Id是隐藏的

<!--Display Comments related to posts-->
<div>
@if (User.Identity.IsAuthenticated)
{
<form asp-action="create" asp-controller="comments" method="post">
@Html.Hidden("PostId", Model.Post.Id)
<div class="form-group">
<label class="h4 ">Add Comments</label>

<textarea name="body" class="form-control" rows="10"></textarea>
</div>
@
<button type="submit" class="btn btn-outline-dark btnReadMore btn-block btn-sm">Submit</button>
</form>
}
else
{
<a class="btn btn-block btn-sm btn-outline-dark btnReadMore" asp-area="identity" asp-page="/Account/Login">
Login To add comments
</a>
}
</div>

能够通过将其包含在我的控制器中来解决它

var nComment = await _context.Comments.Include(p => p.Post).FirstOrDefaultAsync();

现在控制器的操作方法看起来像这个

public async Task<IActionResult> Create([Bind("PostId,Body, Post")] Comment comment)
{
if (ModelState.IsValid)
{

var nComment =  _context.Comments.Include(p => p.Post).FirstOrDefault(p => p.PostId == comment.PostId);
comment.Created = DateTime.Now;
comment.Id = Guid.NewGuid();
//author of the comment
comment.BlogUserId = _userManager.GetUserId(User);
_context.Add(comment);
await _context.SaveChangesAsync();

return RedirectToAction("Details","Posts" , new { slug = nComment.Post.Slug });
}```

最新更新