我查看了一些博客文章,其中包含使用部分视图添加评论的选项。
public class Post
{
[Key]
public int Id { get; set; }
public String Text { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
public class Comment
{
[Key]
public int Id { get; set; }
public int PostId { get; set; }
public String Text { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime AddedOn { get; set; }
[InverseProperty("Comments")]
public virtual Post Post { get; set; }
}
我的详情视图也非常简单:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Model.Data.Post>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<h2>Details</h2>
<fieldset>
<legend>Post</legend>
<div>
<%: Html.DisplayNameFor(model => model.Id) %>
<%: Html.DisplayFor(model => model.Id) %>
</div>
<div>
<%: Html.DisplayNameFor(model => model.Text) %>
<%: Html.DisplayFor(model => model.Text) %>
</div>
</fieldset>
<div id="Comments">
<%: Html.Partial("_CreateComment", new Model.Data.Comment() )%>
</div>
现在有趣的部分,部分视图:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Model.Data.Comment>" %>
<% using (Html.BeginForm()) { %>
<%: Html.AntiForgeryToken() %>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Add Comment</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.Text) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.Text) %>
<%: Html.ValidationMessageFor(model => model.Text) %>
</div>
<p>
<input type="submit" value="Add" />
</p>
</fieldset>
<% } %>
在我的控制器中,我有一个处理新评论的方法:
[HttpPost]
public ActionResult Details(Comment comment)
{
comment.AddedOn = DateTime.Now;
if(ModelState.IsValid)
{
db.Comments.Add(comment);
db.SaveChanges();
return RedirectToAction("Index");
}
}
但由于某些原因,我的新评论Id
设置为与父视图中Id
的{{1}}相同。如何将Post
映射到Post.Id
而不是Comment.PostId
?
我的猜测是它从路由路径到控制器的值,{controller} / {action} / {id}可能是吗?反正是为了防止它发生?我试图在方法中添加Comment.Id
参数,但它仍然映射注释的内部id
,而不仅仅是参数本身......