【发布时间】:2021-04-05 17:56:08
【问题描述】:
我尝试基于另一个控制器创建编辑操作。
但在这种特殊情况下,我做不到。
我的帖子回复没有使用单独的模型,而是根据帖子 ID 保留它。
这是我尝试过的
[Get] Edit 来自控制器的方法:
[Authorize]
[HttpGet]
public IActionResult Edit(int id)
{
var userId = _userManager.GetUserId(HttpContext.User);
if (userId == null)
{
return View("AccessDenied");
}
var rep = _context.PostReplies.Find(id);
if (rep == null)
{
ViewBag.ErrorMessage = $"Post with ID = {rep} cannot be found";
return View("NotFound");
}
PostReply reply = _context.PostReplies.Find(rep);
if (reply == null)
{
return View("NotFound");
}
if (userId == reply.User.Id || User.IsInRole("Admin") || User.IsInRole("Mod"))
{
return View(reply);
}
else
{
return View("NotFound");
}
}
[发布]编辑方法:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit([Bind(include: "Id, Content, Created, Updated")] PostReply reply)
{
if (ModelState.IsValid)
{
_context.Entry(reply).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
_context.SaveChanges();
return RedirectToAction("Manage");
}
return View(reply);
}
这是“模型”PostReply:
using System;
namespace collector_forum.Data.Models
{
public class PostReply
{
public int Id { get; set; }
public string Content { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
public virtual ApplicationUser User { get; set; }
public virtual Post Post { get; set; }
}
}
这在我的 ApplicationDbContext
中声明public DbSet<PostReply> PostReplies { get; set; }
这是我负责显示帖子回复的 HTML 代码部分。
@if (Model.Replies.Any())
{
foreach (var reply in Model.Replies)
{
<div class="row replyContent">
<div class="col-md-3 replyAuthorContainer">
<a class="userName" asp-controller="Profile" asp-action="Detail" asp-route-id="@reply.AuthorId">
@reply.AuthorName
</a>
@if (reply.IsAuthorAdmin && Model.IsAuthorMod)
{
<div class="isAdmin smaller">Admin</div>
}
else if (reply.IsAuthorMod)
{
<div class="isMod smaller">Mod</div>
}
<br />
<span class="postDate">@reply.Date</span>
</div>
<div class="col-md-9 replyContentContainer">
<div class="postContent">
@Html.Raw(reply.ReplyContent)
</div>
</div>
@if (Model.AuthorName.Contains(User.Identity.Name) || User.IsInRole("Admin"))
{
<span class="col-auto">
<a asp-controller="Reply" asp-action="Edit" asp-route-id="@reply.Id" class="btn btn-editPost">
Edit Reply
</a>
</span>
}
else if (Model.AuthorName.Contains(User.Identity.Name))
{
<form asp-action="Delete" asp-controller="Reply" asp-route-id="@reply.Id" method="post">
<button type="submit" class="btn btn-danger"
onclick="return confirm('Are you sure you want to delete post: @Model.Title')">
Delete
</button>
</form>
}
</div>
}
}
点击“编辑”后显示当前代码this error
我的问题出现了,是否可以以不同的方式实施此操作?
//编辑
问题是“Find”函数没有找到除“Id”、“Content”、“Created”、“Updated”之外的其他值。为了让登录的用户编辑他自己的回复,我需要获取用户详细信息并发布详细信息。 userId、UserName、postId..等
这是属性值 - image
【问题讨论】:
-
您能在此处添加ReplyController 类吗?第114 行(请包含该行的整个方法)
-
Method contains line 114 is [HttpGet] Edit Method @madoxdev
标签: c# controller asp.net-core-mvc action