2013-02-05 123 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