我有从DAL检索数据的方法,如下所示:
public List<Comment> GetAllComment(int _UserID)
{
using (var context = new TourBlogEntities1())
{
var AllComment = from s in context.Comments
where s.UserID == _UserID
select s;
return AllComment.ToList<Comment>();
}
}
现在我正试图从我的控制器中调用此方法,如下所示:
[HttpPost]
public ActionResult NewComment(PostComment model)
{
var business = new Business();
var entity = new Comment();
entity.Comments = model.Comments.Comments;
//entity.PostID = model.Posts.PostID; HOW TO PASS POSTID???
entity.UserID = business.GetUserID(User.Identity.Name);
business.PostComment(entity);
var CommentsListFromEntity = business.GetAllComment(business.GetUserID(User.Identity.Name));
var viewmodel = new PostComment();
viewmodel.CommentsListFromModel = CommentsListFromEntity.ToList<CommentInfo>(); // Error is showing here
return View("ViewPost", viewmodel);
}
我将视图与模型绑定,但无法使用列表,即使我尝试将列表本身传递给视图,仍然无法在视图中使用该列表!
我的模型类如下:
public class PostComment
{
public PostComment()
{
Posts = new NewPost();
Comments = new CommentInfo();
User = new UserInfoModel();
}
public NewPost Posts { get; set; }
public CommentInfo Comments { get; set; }
public UserInfoModel User { get; set; }
public List<CommentInfo> CommentsListFromModel { get; set; }
}
那么如何在视图中使用列表?我非常需要帮助!
答案 0 :(得分:1)
您需要从控制器操作返回ActionResult:
public ActionResult GetAllComment(int _UserID)
{
using (var context = new TourBlogEntities1())
{
var AllComment = from s in context.Comments
where s.UserID == _UserID
select s;
return View(AllComment.ToList());
}
}
现在相应的视图可以强烈输入List<Comment>
:
@model List<Comment
然后你可以遍历模型并显示它:
@foreach (var comment in Model)
{
<div><@comment.Text</div>
}
更新:
如果此方法在您的BLL中,您可以在控制器操作中调用它并将结果传递给视图:
public ActionResult SomeAction(int userID)
{
List<Comment> comments = bll.GetAllComment(userID);
return View(comments);
}
更新2:
如果除了此列表之外还需要将其他属性传递给视图,则可以定义包含所有必要信息的视图模型:
public class MyViewModel
{
public List<Comment> Comments { get; set; }
public string Foo { get; set; }
public string Bar { get; set; }
...
}
然后让您的控制器操作将此视图模型传递给视图:
public ActionResult SomeAction(int userID)
{
var model = new MyViewModel();
model.Comments = bll.GetAllComment(userID);
model.Foo = "that's the foo";
model.Bar = "that's the bar";
return View(model);
}
最后您的视图强烈输入新视图模型:
@model MyViewModel
<h2>@Html.DisplayFor(x => x.Foo)</h2>
@foreach (var comment in Model.Comments)
{
<div>@comment.Text</div>
}
<span>@Html.DisplayFor(x => x.Bar)</span>