【发布时间】:2013-12-19 22:17:09
【问题描述】:
我正在开发一个 MVC C# 应用程序。
这是我的代码:
//
// GET: /Comment/Create
[Authorize]
public ActionResult Create(int bookid = 0)
{
var comment = new Comment();
comment.Book = _bookService.GetBookFromBookId(bookid);
comment.Owner = _userService.GetLoggedInUser();
return View(comment);
}
//
// POST: /Comment/Create
[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public ActionResult Create(Comment comment)
{
if (ModelState.IsValid)
{
db.Comments.Add(comment);
db.SaveChanges();
return RedirectToAction("Index","Book",null);
}
return View(comment);
}
在 Get Create ActionResult 中,为 Comment 对象设置 Book 和 Owner 值,但是在 HttpPost Create ActionResult 中,值不在对象中。
我怎样才能让这段代码正常工作?
更新
这是我的查看代码:
@model LearningTestMVCApplication.Models.Comment
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Comment</legend>
<p>
Book Name: @Html.DisplayFor(model => model.Book.Name)
</p>
<div class="editor-label">
@Html.LabelFor(model => model.DisplayText)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.DisplayText)
@Html.ValidationMessageFor(model => model.DisplayText)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
我已经调试了View,对象属性都在那里...
【问题讨论】:
-
您的视图是什么样的?您是否尝试过调试以查看评论对象是否具有预期值?
-
你能发布你的视图的内容吗?在没有看到您的视图的情况下,我会首先查看您输入的“名称”属性,并确保它们与您的评论模型的属性名称匹配。
标签: c# asp.net-mvc view model http-post