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

时间:2014-12-21 11:07:59

标签: c# asp.net-mvc

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

 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。 我尝试使用viewbag,从部分视图表单发送参数,但从那里我无法获得ThreadId。 做正确的方法是什么?我正在考虑创建采用threadId的CreatePostInputModel构造函数,但我不确定这是否是正确的方法。

1 个答案:

答案 0 :(得分:1)

您可以使用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(不要忘记检查DB中是否存在具有此类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 });
}