如何将数据从视图发送到控制器

本文关键字:控制器 视图 数据 | 更新日期: 2023-09-27 18:34:47

我正在制作我的第一个 asp.net mvc项目论坛系统。我正在尝试添加帖子,但我不知道如何将数据从视图发送到控制器。我有我正在使用的视图模型,但我想发送当前 threadId 来发布操作并将其写入数据库。这是我的代码:

 public ActionResult Create(CreatePostInputModel input)
    {
        if (ModelState.IsValid)
        {
             var content = sanitizer.Sanitize(input.Content);
             var post = new Post
             {
                 ThreadId = ViewBag.ThreadId,
                 AuthorId = this.User.Identity.GetUserId(),
                 Content = content,
                 IsDeleted = false,
                 CreatedOn = DateTime.Now,
                 PreserveCreatedOn = true
             };
             this.Data.SaveChanges();
            this.RedirectToRoute("Show thread", new {id = post.ThreadId, name = post.Thread.Title });
        }

public class PostViewModel : IMapFrom<Data.Models.Post>, IHaveCustomMappings
{
    public PostViewModel()
    {
        this.CreatePostInputModel = new CreatePostInputModel();
    }
    public int ThreadId { get; set; }
    public string Title { get; set; }
    public IEnumerable<Data.Models.Post> Posts { get; set; }
    public CreatePostInputModel CreatePostInputModel { get; set; }
    public void CreateMappings(IConfiguration configuration)
    {
        configuration.CreateMap<Data.Models.Post, PostViewModel>()
            .ForMember(m => m.Title, opt => opt.MapFrom(t => t.Thread.Title))
            .ForMember(m => m.ThreadId, opt => opt.MapFrom(t => t.ThreadId));
        configuration.CreateMap<Thread, PostViewModel>()
            .ForMember(m => m.Posts, opt => opt.MapFrom(t => t.Posts))
                .ReverseMap();
    }
}

我的观点

@model IEnumerable<ForumSystem.Web.ViewModels.Post.PostViewModel>
    @{
        ViewBag.Title = "Display";
    }
<div class="container">
        @foreach (var thread in Model)
        {
             ViewBag.ThreadId = thread.ThreadId; 
            <div class="row">
                <h4>@thread.Title</h4>
                @foreach (var post in thread.Posts)
                {
                    <div class="col-md-10">
                        <div class="row">
                                <div>@post.Content</div>
                            <span>
                            </span>
                        </div>
                    </div>
                }
             </div>
                <div>
                    @{ Html.RenderPartial("_CreatePartial", thread.CreatePostInputModel); }
                </div>
        }
</div>

部分视图:

@model ForumSystem.Web.InputModels.Post.CreatePostInputModel
@using (Html.BeginForm("Create", "Post", FormMethod.Post, new { @class = "form-horizontal" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary("", new { @class = "text-danger" })

    <div class="form-group">
        @Html.EditorFor(model => model.Content)
    </div>
    <div class="form-group text-center">
        <input type="submit" value="Добави пост" class="btn btn-primary btn-lg" />
    </div>
}

在 CreatePostInputModel 中,我只有一个字符串属性 Content。我尝试使用视图包,从部分视图表单发送参数,但从那里我无法获得 ThreadId。正确的方法是什么?我正在考虑制作采用threadId的CreatePostInputModel构造函数,但我不确定这是否是正确的方法。

如何将数据从视图发送到控制器

您可以使用

hidden输入字段嵌入当前线程 ID。您需要在分部视图中的窗体中执行此操作。

您的主要观点:

@model IEnumerable<ForumSystem.Web.ViewModels.Post.PostViewModel>
    @{
        ViewBag.Title = "Display";
    }
<div class="container">
        @foreach (var thread in Model)
        {
             ViewBag.ThreadId = thread.ThreadId; 
            <div class="row">
                <h4>@thread.Title</h4>
                @foreach (var post in thread.Posts)
                {
                    <div class="col-md-10">
                        <div class="row">
                                <div>@post.Content</div>
                            <span>
                            </span>
                        </div>
                    </div>
                }
             </div>
                <div>
                    @{ Html.RenderPartial("_CreatePartial", thread); }
                </div>
        }
</div>

您的部分视图:

@modelForumSystem.Web.ViewModels.Post.PostViewModel
@using (Html.BeginForm("Create", "Post", FormMethod.Post, new { @class = "form-horizontal" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary("", new { @class = "text-danger" })
    @Html.HiddenFor(model => model.ThreadId)
    <div class="form-group">
        @Html.EditorFor(model => model.CreatePostInputModel.Content)
    </div>
    <div class="form-group text-center">
        <input type="submit" value="Добави пост" class="btn btn-primary btn-lg" />
    </div>
}

在你的控制器中,只需获取这个id(不要忘记检查数据库中是否存在具有这种threadId的线程(:

public ActionResult Create(int threadId, CreatePostInputModel input)
{
   if (ModelState.IsValid)
   {
      var content = sanitizer.Sanitize(input.Content);
      var post = new Post
      {
                 ThreadId = threadId,
                 AuthorId = this.User.Identity.GetUserId(),
                 Content = content,
                 IsDeleted = false,
                 CreatedOn = DateTime.Now,
                 PreserveCreatedOn = true
      };
      this.Data.SaveChanges();
      this.RedirectToRoute("Show thread", new {id = post.ThreadId, name = post.Thread.Title });
}