简体   繁体   English

在这种情况下如何创建 Edit 方法? ASP.NET 核心 MVC

[英]How to create an Edit method in this situation? ASP.NET Core MVC

I tried to create an Edit action based on another controller.我试图根据另一个 controller 创建一个编辑操作。

But in this particular case, I can't do it.但在这种特殊情况下,我做不到。

I don't use a separate model for my post replies, but keep it based on the post ID.我的帖子回复没有使用单独的 model,而是根据帖子 ID 保留它。

This is what I tried这是我试过的

[Get] Edit method from controller: [获取] 来自controller的编辑方法:

[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");
            }
        }

[Post] Edit method: [帖子]编辑方法:

[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);
        }

This is "model" PostReply :这是“模型” 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; }
    }
}

Which is declarated in my ApplicationDbContext这是在我的ApplicationDbContext中声明的

public DbSet<PostReply> PostReplies { get; set; }

This is my part of HTML code resposible for displaying post replies.这是我负责显示帖子回复的 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>
        }
    }

With the current code after clicking "Edit" this error shows up单击“编辑”后使用当前代码显示此错误

And here my question arises, is it possible to implement this action in a different way?在这里我的问题出现了,是否有可能以不同的方式实施这个行动?

//EDIT //编辑

Problem is that the function "Find" doesn't find other values except "Id", "Content", "Created", "Updated".问题是 function“Find”没有找到除“Id”、“Content”、“Created”、“Updated”之外的其他值。 To let logged user to edit his own reply I need to get user details and post details ex.为了让登录用户编辑自己的回复,我需要获取用户详细信息并发布详细信息,例如。 userId, UserName, postId.. etc. userId, UserName, postId..等

This are values of properties - image这是属性值 -图片

You can change your Edit Action like this:您可以像这样更改您的编辑操作:

[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");
            }

            if (userId == rep.User.Id || User.IsInRole("Admin") || User.IsInRole("Mod"))
            {
                return View(rep);
            }
            else
            {
                return View("NotFound");
            }
        }

You have got rep with _context.PostReplies.Find(id);你有代表_context.PostReplies.Find(id); ,So you don't need to use PostReply reply = _context.PostReplies.Find(rep); ,所以你不需要使用PostReply reply = _context.PostReplies.Find(rep); , and check if it is null again,also you need to put an int type rather than PostReply into _context.PostReplies.Find(xxx) . ,并再次检查它是否是 null ,您还需要将 int 类型而不是PostReply放入_context.PostReplies.Find(xxx)

  public async Task<IActionResult> Update(int? id)
    {
        ViewBag.Positions = new SelectList(_context.Positions, nameof(Position.Id), nameof(Position.Name));
        var employee =await _context.Employees.FirstOrDefaultAsync(x => x.Id == id);
        if (employee == null) { return NotFound(); }
        UpdateEmployeeVM employeeVM = new UpdateEmployeeVM
        {
            Name = employee.Name,
            Surname = employee.Surname,
            PositionId = employee.PositionId,
            FacebookUrl = employee.FacebookUrl,
            TwitterUrl = employee.TwitterUrl,
            InstagramUrl = employee.InstagramUrl,
            Salary = employee.Salary,
            ImgUrl=employee.ImageUrl
        };
        return View(employeeVM);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NEt MVC中的DropDownList编辑方法 - DropDownList in ASP.NEt MVC Edit method 如何在ASP.NET MVC 5中通过视图创建/编辑模型 - How to create/edit models via view in asp.net mvc 5 如何创建我在ASP.net MVC中以VARBINARY数据类型存储在数据库中的图像的EDIT方法和EDIT Razor View? - How to create EDIT method and EDIT Razor View for Image which i stored in database in VARBINARY datatype in ASP.net MVC? 如何在 ASP.NET Core MVC 中的 Edit 方法的下拉字段中显示 selectedValue(来自数据库) - How can I display the selectedValue (from database) in a dropdown-field from the Edit method in ASP.NET Core MVC 如何在 ASP.NET Core MVC 中创建具有多个图像的产品 - How to create product with multiple images in ASP.NET Core MVC 如何在 EF 和 ASP.NET Core 5 MVC 中创建表? - How I create a table in EF and ASP.NET Core 5 MVC? 如何在 ASP.NET Core 6 MVC 中创建启动 class - How to create Startup class in ASP.NET Core 6 MVC 如何在ASP.Net Core MVC中创建级联SelectList - How to create a cascading SelectList in ASP.Net Core MVC 如何在ASP.NET Core中创建MVC5 MvcHtmlString - How to create a MVC5 MvcHtmlString in ASP.NET Core 如何从 ASP.NET Core MVC 中的视图创建 object - How to create an object from the view in ASP.NET Core MVC
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM