0

我正在尝试使用 MVC 4 创建一个博客,现在我在将 postid 发送到评论创建页面并将其隐藏起来时遇到问题,直到我点击创建以创建带有帖子 ID 的评论

这是评论创建视图

@model MVCProjectApp.Models.Comment

@{
    ViewBag.Title = "Create Comment";
}

<h2>Create</h2>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Comments</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Username)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Username)
            @Html.ValidationMessageFor(model => model.Username)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Message)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Message)
            @Html.ValidationMessageFor(model => model.Message)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Timestamp)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Timestamp)
            @Html.ValidationMessageFor(model => model.Timestamp)
        </div>


        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "~/FullPost/Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

这是我将 postid 传递给评论创建的 Actionlink

 @Html.ActionLink("Comment", "Create", "Comment", ID, null)

这是评论控制器

 //
        // GET: /Comment/Create

        public ActionResult Create()
        {
            ViewBag.PostID = new SelectList(db.Posts, "PostID", "Title");
            return View();
        }

        //
        // POST: /Comment/Create

        [HttpPost]
        public ActionResult Create(Comment comment)
        {
            if (ModelState.IsValid)
            {
                db.Comments.Add(comment);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.PostID = new SelectList(db.Posts, "PostID", "Title", comment.PostID);
            return View(comment);
        }

这是评论模型

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCProjectApp.Models
{
    public class Post
    {
        public int PostID { get; set; }
        public string Title { get; set; }
        public string Message { get; set; }
        public DateTime Timestamp { get; set; }
        public virtual ICollection<Comment> Comments { get; set; }
    }
    public class Comment
    {
        public int CommentID { get; set; }
        public int PostID { get; set; }
        public string Username { get; set; }
        public string Message { get; set; }
        public DateTime Timestamp { get; set; }
        public virtual Post Post { get; set; }
    }
}
4

1 回答 1

0

使用 Html.HiddenFor() (如上面的评论中所述)来保存您需要从视图返回给您但不想显示的值。

请记住,这是可破解的。采取适当的措施以确保您传递给视图的 ID 与返回的 ID 相同。查找 AntiForgeryToken。

于 2012-12-04T22:15:17.573 回答