2

我需要将多个模型传递给一个视图,并且我希望视图是强类型的(因此,如果我可以帮助它,我想在不使用将每个模型传递给 ViewBag 的情况下这样做)。

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 并将模型传递给查看。当我去编译我的项目时,我得到了几十个错误(见下文),我该如何解决这个问题?我只是希望能够从我的视图中访问封装在另一个类中的多个模型。提前致谢。

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.
...
4

1 回答 1

0

如果我遗漏了编码技巧或模式,请原谅我,但为什么在“TestModels”类内有“TestDetail”类?

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

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

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
于 2013-02-06T19:47:17.880 回答