【问题标题】:MVC3 error when passing a model from controller to view while using a viewModel使用 viewModel 时将模型从控制器传递到视图时出现 MVC3 错误
【发布时间】:2012-08-02 17:34:15
【问题描述】:

对不起,我确信有一种方法可以使用 viewModel 来做到这一点,但是我对此非常缺乏经验,甚至不知道我是否做得正确。

我想要做的是将多个博客和发布每个博客的用户的个人资料信息传递给一个视图。

我收到以下错误。

传入字典的模型项是类型 'ACapture.Models.ViewModels.BlogViewModel',但是这本字典 需要类型的模型项 'System.Collections.Generic.IEnumerable`1[ACapture.Models.ViewModels.BlogViewModel]'。

我正在尝试将以下查询结果传递给视图。

        var results = (from r in db.Blog.AsEnumerable()
                       join a in db.Profile on r.AccountID equals a.AccountID
                       select new { r, a });

        return View(new BlogViewModel(results.ToList()));
    }

这是我的视图模型

public class BlogViewModel
{
    private object p;

    public BlogViewModel(object p)
    {
        this.p = p;
    }
}

我的看法

@model IEnumerable<ACapture.Models.ViewModels.BlogViewModel>
@{
    ViewBag.Title = "Home Page";
}

<div class="Forum">
    <p>The Forum</p>

            @foreach (var item in Model)
            {
                <div class="ForumChild">


                    <img src="@item.image.img_path" alt="Not Found" />
                    <br />
                        <table>
                            @foreach (var comment in item.comment)
                            {

                                <tr><td></td><td>@comment.Commentation</td></tr>
                            }
                        </table>
                </div>                
            }
</div>

提前致谢。

【问题讨论】:

    标签: asp.net-mvc-3 linq entity-framework-4


    【解决方案1】:

    我想你需要稍微改变一下你的视图模型:

    public class BlogViewModel
    {
        public Blog Blog { get; set; }
        public Profile Profile{ get; set; }
    }
    

    然后返回如下:

        var results = (from r in db.Blog.AsEnumerable()
                       join a in db.Profile on r.AccountID equals a.AccountID
                       select new new BlogViewModel { Blog = r, Profile = a });
    
        return View(results.ToList());
    

    然后在视图内部的foreach 循环中,您将获得一个包含个人资料和博客信息的对象,因此您可以像 f.e. 一样使用它。 @item.Profile.Username

    【讨论】:

      【解决方案2】:

      我不完全确定在这种情况下您要使用 ViewModel 完成什么,但您似乎希望该页面代表一个包含 cmets 集合的单个博客。在这种情况下,您应该更换

      IEnumerable<ACapture.Models.ViewModels.BlogViewModel>
      

      ACapture.Models.ViewModels.BlogViewModel
      

      然后Model 表示单个 BlogViewModel,您可以使用 Model.comments 遍历 cmets 并使用 Model.image.img_path 访问图像。

      如果不是这种情况,并且您打算每个页面有多个 BlogViewModel,那么您将不得不实际构建一个 BlogViewModel 集合并将其传递给视图。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-30
        • 1970-01-01
        • 2021-12-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多