如何在mvc中将id传递给控制器

时间:2016-06-19 16:03:22

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

我有一个名为model的{​​{1}}图片,其中有一个名为PostID的属性,另一个model名为post。在列表view中,当用户点击帖子向其添加图片时,它会通过PostID

传递HtmlActionLink

@Html.ActionLink("Add Images", "AddImages", new { id = item.PostID })

它工作正常,但我也需要将PostId保存在图片Model中。

    public ActionResult AddImages(int id)
    {
        ImageViewModel images = new ImageViewModel();
        images.PostID = id;           
        return View(images);
    }
    [HttpPost]
    public ActionResult AddImages(ImageViewModel image, HttpPostedFileBase images)
    {            
        Image newImage = new Image();
        newImage.PostID = image.PostID;
        return View("Index");
    }

这种方式不起作用,保存时,PostID的值为0.我也尝试使用ViewBag,但到目前为止没有运气。在AddImages View中,没有TextBoxForPostID属性的任何内容,因为用户不会设置或看到它。

2 个答案:

答案 0 :(得分:4)

为了在HttpPost操作中获取PostID,您应该在视图的表单标记中添加PostId的输入字段。

@Html.HiddenFor(m=>Model.PostId)

答案 1 :(得分:1)

是的,PostID未由用户设置,但您仍需要将其放在<form>中,以便在HttpPost中回发到服务器。通常,我们会使用hidden field。有点像:

<form>
    @Html.HiddenFor(m => Model.PostID)

    <!-- Other fields here -->
</form>