2013-02-05 96 views
2

我需要传递多个模型到一个视图,我希望视图是强类型的(所以如果我可以帮助它,我想这样做而不使用传递我的模型中的每一个ViewBag)。ASP.NET MVC 4模型封装渲染查看错误

Public Class TestModels 
    Public Class TestDetail 

     Public firstModel As firstModelHere ' An entity 
     Public secondModel As secondModelHere ' An entity 

     Sub New() 
      firstModel = Nothing 
      secondModel = Nothing 
     End Sub 

    End Class 
End Class 

其中我有它自己的独立文件中的模型目录。我封装的模式传递给我的看法,像这样:

@ModelType Website.TestModels.TestDetail 
@Html.LabelFor(Function(model) model.firstModel.userName) 
@Html.LabelFor(Function(model) model.secondModel.lastName) 

我设置firstModel和secondModel在我的控制器,并通过该模型进行查看。当我去编译我的项目时,我有几十个错误(见下文),我该如何解决这个问题?我只是希望能够访问我的Views中封装在另一个类中的多个模型。提前致谢。

Error 134 'ViewBag' is not declared. It may be inaccessible due to its protection level. 
Error 129 'Context' is not declared. It may be inaccessible due to its protection level. 
Error 138 'Layout' is not declared. It may be inaccessible due to its protection level. 
Error 131 sub 'Execute' cannot be declared 'Overrides' because it does not override a sub in a base class. 
... 

回答

0

原谅我,如果我缺少一个编码技巧或图案,但为什么你有这个类的TestDetail'类“TestModels”里面?

如果您只是想将多个模型传递给视图,那么我会制作单视图模型,并为每个要传递给视图的实体分配一个属性。

视图模型 - 用于封装要在您的视图访问

Public Class TestModel 
    Public Property FirstModel As FirstEntity ' An entity 
    Public Property SecondModel As SecondEntity ' An entity 
End Class 

控制器动作模式

Function Index() As ActionResult 
    ' Create models to pass to the view. 
    Dim a As New FirstModel 
    Dim b As New SecondModel 

    ' Create model to pass the models in. 
    Dim model As New TestModel 
    With model 
     .firstModel = a 
     .secondModel = b 
    End With 

    Return View(model) 
End Function