繁体   English   中英

ASP.NET Core MVC 如何将 ViewModel 发送到不同的控制器方法

[英]ASP.NET Core MVC How to send ViewModel to different controller method

所以我有 2 个控制器类;

公告控制器,这只是生成一个主页,上面有来自用户的帖子。

// GET: Announcements
    public async Task<IActionResult> Index()
    {
        var announcements = await _context.Announcement.ToListAsync();
        announcements = announcements.OrderByDescending(x => x.CreatedOn).ToList();
        foreach (var ann in announcements)
        {
            ann.TimeAgo = ann.CreatedOn.TimeAgo();
        }
        
        var users = await _context.Users.ToListAsync();
        var comments = await _context.Comment.ToListAsync();
        AnnouncementAndCommentsViewModel aacVM = new AnnouncementAndCommentsViewModel();

        AnnouncemenstViewModel announcemenstViewModel = new AnnouncemenstViewModel();
        announcemenstViewModel.Announcement = announcements;
        announcemenstViewModel.User = users;
        announcemenstViewModel.Comment = comments;

        CommentViewModel commentViewModel = new CommentViewModel();

        aacVM.announcemenstViewModel = announcemenstViewModel;
        aacVM.commentViewModel = commentViewModel;

        ViewData.Add("currentUserID",GetCurrentUser().Id);

        return View(aacVM);
    }

然后我有 CommentsController

[HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(CommentViewModel commentViewModel)
    {
        if (ModelState.IsValid)
        {
            var comment = new Comment();
            comment.CreatedOn = DateTime.Now;
            comment.Body = commentViewModel.Comment.Body;

            Announcement announcement = GetAnnouncement(commentViewModel.Announcement.AnnouncementID);
            comment.Announcement = announcement;
            ApplicationUser user = GetCurrentUser();
            comment.User = user;

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

从我的公告控制器索引视图中,我有一个帖子列表,然后我希望能够直接在该视图中编写和添加评论,而不是转到另一个视图。

我有 2 个 ViewModel,一个用于存储公告,一个用于评论。

我正在尝试使用接受 CommentViewModel 的参数调用 Comments Controller 中的 Create Post 方法,尽管我无法弄清楚。 我一直被发送到填充了正文的 Create Get 方法。

这是我的索引视图以及我如何尝试将数据发布到 CommentsController

@model Treharris.Models.AnnouncementAndCommentsViewModel;
.
.
.
@foreach (var item in Model.announcemenstViewModel.Announcement)
        {
.
.
.
<div class="announcement-body">
                    <p>@Html.DisplayFor(modelItem => item.Body)</p>
                </div>
                <div class="comments">
                    <p id="comment">Comments</p>
                    @using(Html.BeginForm("Create","Comments", FormMethod.Post, 
                     new { cvm = Model.commentViewModel }))
                    {
                        @@Model.commentViewModel.Announcement = item;
                        @Html.HiddenFor(m => m.commentViewModel.Announcement)
                        @Html.TextBoxFor(m => m.commentViewModel.Comment.Body, 
                        new { placeholder = "Comment body" })
                        <input type="submit" value="Create" />

                    }

正如@Shyju 评论的那样,要使模型绑定使用表单扩展工作,传递给视图的模型必须与发布操作接收的模型相同。

如果您查看生成的 HTML,

@Html.HiddenFor(m => m.commentViewModel.Announcement)

输出一些东西

<input type="hidden" name="commentViewModel.Announcement" value="propVal" />

在操作你期望CommentViewModel一个没有命名的属性对象commentViewModel ,但有一个属性命名Announcement 这就是绑定不会发生的原因。

要么更改 post action 方法上的参数以匹配 View Model,但请注意,表单上不存在的所有属性都将发布为 null,

删除 .NET Core 中不推荐使用的 Html 表单扩展方法,并为这些类型的绑定使用简单的 Html,如下所示:

<form asp-controller="Comments" asp-action="Create" method="post">
        <input type="hidden" name="Announcement" value="@Model.commentViewModel.Announcement" />
        <input type="text" name="Comment.Body" placeholder="Comment body" value="@Model.commentViewModel.Comment.Body" />
        <input type="submit" value="Create" />
</form>

请记住将有关Announcement对象的所有信息包含在隐藏字段中,因为您无法像尝试那样在表单上发布复杂的对象。 这是 HTML 功能/限制。

例如,简单地在表单中包含公告 ID,如下所示:

<input type="hidden" name="Announcement.Id" value="@item.id" />

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM