【发布时间】:2017-01-21 19:20:08
【问题描述】:
我正在尝试启用从我按 id 显示论坛帖子的视图中发布评论。这就是我的视图收到的模型:
@model PostViewModel
模型具有和“Id”属性,我使用 javascript 将其发送到控制器:
<script>
$("#target").click(function () {
$("#formPlace").load('@Url.Action("AddComment","Posts", new { postId = Model.Id })');
});
</script>
这就是我将“postId”发送到的控制器操作:
[HttpGet]
public ActionResult AddComment(int postId)
{
var comment = new CommentViewModel();
comment.PostId = postId;
return this.PartialView("_AddComment", comment);
}
此视图返回一个用户必须填写评论内容的表单:
@model MvcTemplate.Web.ViewModels.Posts.CommentViewModel
<div>
@using (Html.BeginForm("AddComment", "Posts", FormMethod.Post))
{
<div>Enter your comment here:</div>
<div>
@Html.TextAreaFor(x => Model.Content)
</div>
<input type="submit" name="Submit" />
}
</div>
当视图接收到模型时,它的“PostId”仍然是正确的 = 我用 javascript 设置的。但是,在用户提交表单后,发送到控制器的 CommentViewModel 的“PostId”为 0(默认 int 值)。这是控制器动作:
[HttpPost]
public ActionResult AddComment(CommentViewModel viewModel)
{
// transfer the view model to db model and save;
}
知道如何保持正确的 PostId 吗?
【问题讨论】:
-
我可以看看
CommentViewModel的代码吗?