我正在使用具有模型實作遞回的 .NET MVC,如下所示:
public class Comment
{
[Key]
[Required]
public int CommentId { get; set; }
[Required]
public string Content { get; set; }
public bool Anonymous { get; set; }
[Required]
public DateTime Created_date { get; set; }
[Required]
public DateTime Last_modified { get; set; }
public virtual Comment Reply { get; set; }
public virtual ICollection<Comment> Replys { get; set;}
public virtual Idea Idea { get; set; }
}
在解釋中,每個 Idea 內部都包含不同的 Comments,并且每條評論還有幾個較小的 Comments 來回復前一個。但是,我不知道如何進行遞回以獲取評論的回復和每個回復的較小回復,直到控制器中的最后一個回復以及如何在視圖中顯示它們。請隨時問我任何問題,因為我的解釋有時不清楚。
public ActionResult Index(int? i)
{
List<Idea> Ideas = db.Ideas.ToList();
foreach(Idea idea in Ideas)
{
idea.Comments = db.Comments.Include(x => x.Reply).ToList();
idea.Comments=idea.Comments.Where(x => x.Idea == idea).ToList();
foreach (Comment comment in idea.Comments)
{
comment.Replys = GetComments(comment.CommentId); //This function use to get list of reply for comment
foreach (Comment reply in comment.Replys)
{
reply.Replys=GetComments(reply.CommentId);
foreach (Comment reply2 in reply.Replys)
{
reply2.Replys=GetComments(reply2.CommentId);
foreach(Comment reply3 in reply2.Replys)
{
reply3.Replys = GetComments(reply3.CommentId);
//When would this stop ?
}
}
}
}
}
return View(Ideas.ToPagedList(i ?? 1, 5));
}
uj5u.com熱心網友回復:
使用這個回圈;
foreach(Idea idea in Ideas)
{
idea.Comments = db.Comments.Include(x => x.Reply).ToList();
idea.Comments= idea.Comments.Where(x => x.Idea == idea).ToList();
foreach (Comment comment in idea.Comments)
{
RecursionGetComments(comment);
}
}
添加此功能;
public void RecursionGetComments(Comment comment){
comment.Replys = GetComments(comment.CommentId);
foreach(var reply in comment.Replys){
RecursionGetComments(reply);
}
}
如果RecursionGetComments上面沒有正確填寫,您可能需要使用ref傳遞類當前實體的關鍵字(通過參考傳遞);
public void RecursionGetComments(ref Comment comment){
comment.Replys = GetComments(comment.CommentId);
foreach(var reply in comment.Replys){
RecursionGetComments(reply);
}
}
我還注意到在您的模型中,您使用的是關鍵字virtual。
Virtual指示導航屬性將自動加載/延遲加載的物體框架,因為您正在手動加載評論,您可以將其洗掉。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/441297.html
標籤:C# asp.net-mvc 递归
上一篇:jQueryajax將null傳遞給ASP.NETMVC中的控制器
下一篇:ASP.Net找不到新添加的視圖
