2010-04-30 94 views
0

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

我的问题是,在查看模型。在任何视图(连接到母版的的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]'. 

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

所以,我的问题是:我可以创建一个包含部分视图模型的模型吗? 如果,是的,那样?

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

感谢您的帮助

+0

我以前碰到过这个。请发布视图的标题和RenderPartialView代码 – hunter 2010-04-30 15:44:28

回答

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

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