C# .NETMVC中的Where子句
我有下面的代码从数据库中选择了一堆评论,但是我只有一篇当前的帖子,我只想处理关于当前帖子的评论C# .NETMVC中的Where子句,c#,asp.net-mvc,linq,http-post,C#,Asp.net Mvc,Linq,Http Post,我有下面的代码从数据库中选择了一堆评论,但是我只有一篇当前的帖子,我只想处理关于当前帖子的评论 public ActionResult Index() { ViewBag.PostCommentFK = new SelectList(db.Posts, "PostID", "PostTitle"); return View(); } 我想我只需要在语句中添加一个where子句,“PostCurrent”是一个布尔值,并且只能有一个“True”PostCurrent 目前在我看来
public ActionResult Index()
{
ViewBag.PostCommentFK = new SelectList(db.Posts, "PostID", "PostTitle");
return View();
}
我想我只需要在语句中添加一个where子句,“PostCurrent”是一个布尔值,并且只能有一个“True”PostCurrent
目前在我看来,我有一个值为1的隐藏字段,所以评论只添加到帖子1中,但我希望这是当前的帖子
@Html.HiddenFor(model => model.PostCommentFK, new { Value = 1 })
然后我有了一个[HttpPost]
方法来保存更改
[HttpPost]
public ActionResult Index(Comment comment)
{
if (ModelState.IsValid)
{
db.Comments.AddObject(comment);
db.SaveChanges();
return RedirectToAction("CommentResponse");
}
ViewBag.PostCommentFK = new SelectList(db.Posts, "PostID", "PostTitle", comment.PostCommentFK);
return View(comment);
}
我认为您需要隐藏
PostID
而不是value
@Html.HiddenFor(model => model.PostCommentFK.PostID)
然后:
[HttpPost]
public ActionResult Index(Comment comment)
{
if (ModelState.IsValid)
{
if(comment.PostID == 0)//New record
db.Comments.AddObject(comment);
else // Edit existing comment
{
var OldComment = db.Comments.Where(c => c.PostID == comment.PostID).SingleOrDefault();
if (OldComment != null)
{
OldComment.PostTitle = comment.PostTitle;
//Set all other properties...
}
}
db.SaveChanges();
return RedirectToAction("CommentResponse");
}
ViewBag.PostCommentFK = new SelectList(db.Posts, "PostID", "PostTitle", comment.PostCommentFK);
return View(comment);
}
谢谢你,阿门
你离我很近,它为我指明了正确的方向。我遇到的问题是,在我看来,我使用的是评论模式,但需要后模式。视图发布评论,但只是一个表单,只需要知道当前帖子的posted
所以我把我的索引操作改为
public ActionResult Index()
{
Post post = db.Posts.Single(p => p.PostCurrent == true);
return View(post);
}
并给出了我的观点
@model TMPBlog.Models.Post
然后我就可以像这样访问post了
@Html.Hidden("PostCommentFK", @Html.DisplayFor(model => model.PostID))
干杯
Mike.你的问题是什么?我如何检索当前帖子的PostID并将其插入新评论的FK字段?PostCurrent是Post表中的一个布尔字段。我无法使其工作,因为我没有在任何阶段选择CurrentPosts、PostID。