将评论绑定到当前页面

时间:2015-03-15 03:51:11

标签: c# asp.net entity-framework asp.net-mvc-5

我目前正在从我的大学完成一项任务。任务是使用asp.net mvc构建一个评论系统。所以我建立了一个图像库,除了评论之外,一切都很顺利。

我的问题是评论与特定图片有关,但我不确定如何将用户和图片对象从视图传递回控制器。

PictureModel.cs

public class Picture
{
    [Required]
    public virtual int PictureId { get; set; }

    public virtual User User { get; set; }
    public virtual ICollection<Comment> Comments { get; set; }
}

CommentModel.cs

public class Picture
{
    [Required]
    public virtual int CommentId { get; set; }

    [Required]
    public virtual int UserId { get; set; }

    [Required]
    public virtual string Body { get; set; }

    [Required]
    [DataType(DataType.DateTime)]
    [DisplayFormat(DataFormatString = "{0:dd MMMM yyyy - HH:MM}", ApplyFormatInEditMode = true)]
    public virtual DateTime PostTime { get; set; }

    public virtual User User { get; set; }
    public virtual Picture Picture { get; set; }
}

PictureDetailsViewModel.cs

public class PictureDetailsViewModel
{
    public User currentUser { get; set; }
    public Picture picture { get; set; }
    public string comment { get; set; }
}

PictureController.cs

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Comment(PictureDetailsViewModel model)
{
    if (ModelState.IsValid)
    {
        if(model.comment != null) {
            var comment = new Comment { User = model.currentUser, Picture = model.picture, Body = model.comment, PostTime = DateTime.Now };
            db.Comments.Add(comment);
            db.SaveChanges();
        }

        return RedirectToAction("Details", new { id = model.picture.pictureID });
    }
    else
    {
        return RedirectToAction("Index");
    }
}

图片/ details.cshtml

using (Html.BeginForm("Comment", "Picture", null, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    @Html.TextBoxFor(model => model.comment, new { @class = "form-control", @placeholder = "Write a comment..." })
    <input type="submit" class="form-control input-button" value="Submit" />
}

当我提交表单时,我的控制器映射到正确的操作,但我的模型缺少图片和用户的值,如下所示:

model.currentUser = null;
model.picture = null;
model.comment = "test";

如何从模型中提取用户和图片?

0 个答案:

没有答案