强类型局部视图的问题

时间:2010-04-30 15:39:52

标签: asp.net-mvc

我的部分视图存在问题。 我正在asp.net mvc开发一个博客,我会在我的主页上列出一个类别列表,最后发表的帖子,最后的评论。 我认为最好的解决方案是使用强类型的局部视图,并在每个局部视图中传递必要的模型。

我的问题是View ..在任何视图(连接到母版页的contentplaceholder)中的模型与部分视图中的模型冲突,我得到如下错误:

The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[Blog.Models.Articoli]' but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[Blog.Models.Categorie]'. 

我在网上发现了一个肮脏的解决方案,包括传递任何视图的模型,一些视图数据,每个模型都可以在局部视图中传递。但是这个解决方案不尊重DRY原则。因为你必须为每个动作重复这个代码!

所以,我的问题是:我可以创建一个包含局部视图模型的模型吗? 如果,是的,以这种方式?

它还存在另一种更简单的解决方案吗?

感谢您的帮助

2 个答案:

答案 0 :(得分:5)

视图模型模式怎么样?

我创建了传递给我的视图的包装类,而不是我通常使用的任何对象

public class MyCreateUserView
{
    public User CreatingUser { get; set; }
    public MyPartialViewObject Blah { get; set; }
}

在你的视图中写道:

public ActionResult CreateUser()
{
    MyCreateUserView createUser = new MyCreateUserView()
    {
        CreatingUser = GetUserFromSomewhere(),
        Blah = GetPartialViewObject();
    }

    return View(createUser);
}

然后你的页面标题如下:

<%@ Page Language="C#" Inherits="ViewPage<MyCreateUserView>" %>

当你渲染部分写作时:

<% Html.RenderPartial("../MyPartialViewObject ", Model.Blah); %>

答案 1 :(得分:1)

我没有用您描述的模式(通常是一个很好的模式)来解决这个问题,而是通过调用RenderAction来解决这个问题并让它返回局部视图。这样代码就在一个地方,因为每次调用每个视图都不必担心编组所需的所有数据。如果你想看一个关于如何使用它的简短讨论,我会在这里查看Haack的博客:http://haacked.com/archive/2009/11/18/aspnetmvc2-render-action.aspx。您还可以在SO:ASP.NET MVC Master Page Data

上查看此其他帖子的讨论