我有一个文章模型和一个评论模型。ArticleDetail视图显示文章、文章评论和创建新评论的公式。
当为一篇文章创建新评论时,它与文章具有相同的id。在公共评论( ActionResult DisplayCreateComment,CommentModel articleID)中,CommentModel与文章具有相同的ID。
所以每个帖子的评论都会有相同的ID,这是行不通的。为什么评论和这篇文章有相同的id,我该如何解决这个问题?
CommentModel:
public class CommentModel
{
public int ID { get; set; }
public string Text { get; set; }
public DateTime DateTime { get; set; }
public Article Art { get; set; }
}ArticleModel:
public class ArticleModel
{
public int ID { get; set; }
public DateTime DateTime { get; set; }
public ICollection<CommentModel> Comments { get; set; }
public string Text { get; set; }
public string Title { get; set; }
...
}ArticleDetail视图:
...
@Html.Partial("DisplayComments", Model.Comments)
@Html.Action("DisplayCreateComment", "Home", new { articleID = Model.ID })
...HomeController:
public ActionResult DisplayCreateComment(int articleID)
{
return PartialView();
}
[HttpPost]
public ActionResult DisplayCreateComment(CommentModel comment, int articleID)
{
...
//There the CommentModel has the same ID as the Article Model ...
}发布于 2013-05-17 03:18:37
您的CommentModel中需要有ArticleId。在已有内容的基础上,将以下内容添加到CommentModel中。
[ForeignKey("ArticleModel"), DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ArticleId { get; set; }
public virtual ArticleModel ArticleModel { get; set; }有关您的问题的更多帮助,请单击此处:
Matt Blagden From Zero to Blog in 100 Minutes。这可以帮助您创建整个博客,但它不使用Entity Framework Code First。
Scott Allen's Plural Sight Video。有一个试用版可以使用。这将向您展示如何实现one-to-many对象。有Department和Employee,你可以创建你的部门(文章),然后能够以同样的方式添加员工(评论)。
基本上,你必须先创建你的文章,然后添加评论,而在文章的细节。你所要做的就是有一个Create link inside文章细节。
@Html.ActionLink("Create an comment", "Create", "Comment",
new {ArticleId = @Model.ArticleId}, null)在Models文件夹/ViewModels文件夹中创建CommentViewModel类
public class CreateCommentViewModel
{
[HiddenInput(DisplayValue = false)]
public int ArticleId { get; set; }
[Required]
public string Text { get; set; }
}然后,让您的创建操作在评论控制器中如下所示;
[HttpGet]
public ActionResult Create(int articleId)
{
var model = new CreateCommentViewModel();
model.ArticleId= articleId;
return View(model);
}
[HttpPost]
public ActionResult Create(CreateCommentViewModel viewModel)
{
if(ModelState.IsValid)
{
var db = new EfDb();
var article= _db.Articles.Single(d => d.Id == viewModel.ArticleId);
var comment= new Comment();
comment.Text = viewModel.Text;
comment.DateTime = DateTime.UtcNow;
article.Comments.Add(comment);
db.SaveChanges();
return RedirectToAction("detail", "article", new {id = viewModel.ArticleId});
}
return View(viewModel);
}https://stackoverflow.com/questions/16594369
复制相似问题