1

我有从 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; }

}

那么如何使用视图中的列表呢?我非常需要帮助!

4

1 回答 1

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>
于 2012-10-15T09:59:29.413 回答