在没有automapper的情况下将Model转换为ViewModel

时间:2013-05-02 18:55:12

标签: c#

嗨,这是我将模型的Ilist转换为ViewModel方法的Ilist

public static IList<PostViewModel> ConvertToPostViewModelList(this IList<Post> posts)
        {
            return posts.Select(ConvertToPostViewModel).ToList();
        }

这也是ConvertToPostViewModel

 public static PostViewModel ConvertToPostViewModel(this Post post)
        {
            var blogPostViewModel = new PostViewModel
                {
                    Id = post.Id,
                    Body = post.Body,
                    Summary = post.Summary,
                    Title = post.Title,
                    Category = post.Category,
                    CreationDate = post.CreationDate,
                    SelectedCategory = post.CategoryId,
                    SelectedTag = post.TagId,
                    Tag = post.Tag,
                    UrlSlug = post.UrlSlug

                };

            return blogPostViewModel;
        }

这有什么问题,我收到了这个错误查看:

The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[Blog.Domain.Model.Post]', but this dictionary requires a model item of type 'System.Collections.Generic.IList`1[Blog.Web.UI.ViewModels.PostViewModel]'.

然后??我通过这个将模型的Ilist转换为ViewModel:

return posts.Select(ConvertToPostViewModel).ToList();

然后发生了什么?

我在行动中做了什么

 public ActionResult  Posts()
        {
            var blogPost = _blogRepository.GetAllPost();
            var blogPostViewModel = blogPost.ConvertToPostViewModelList();
            return View("Posts", blogPostViewModel);
        }

并在视图中

@model IList<Blog.Web.UI.ViewModels.PostViewModel>

1 个答案:

答案 0 :(得分:0)

两种可能性:

  1. 您发布的方法不是匹配的方法。您可以通过在控制器操作中抛出异常并查看是否被抛出来轻松验证这一点。这可能是以下任一结果:(a)一个重载的Posts控制器动作,其中另一个正在匹配;或者,(b)拦截请求的自定义路线。

  2. 您最初在测试中返回了域对象,但在更改控制器操作以将模型设置为PostViewModel后,您忘记重新编译MVC项目。尝试重新编译您的解决方案,看看结果是否发生了变化。