我正在尝试使用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; }
}
}
答案 0 :(得分:0)
使用Html.HiddenFor()(如上面的注释中所述)来保存您需要从视图中返回但不想显示的值。
请记住,这是可以攻击的。采取适当措施确保传递给视图的ID与返回的ID相同。查看AntiForgeryToken。