2017-07-19 78 views
0

我有3個型號。 1模型用於搜索框休息2我用於顯示覆選框列表。如何在單個視圖中添加多個模型?

的搜索框,我不想IEnumerable的類型模型,但對於複選框,我想了IEnumerable類型的模型

數據從不同的控制器 來我怎樣才能做到這一點在一個單一的視圖?

請舉一些例子。

+0

構築「大「模型,其中包含所有這些模型。 – jAC

+0

您需要使用'ViewModel' https://docs.microsoft.com/zh-cn/aspnet/mvc/overview/older-versions/mvc-music-store/mvc-music-store-part-3 –

+0

嘗試創建**一個模型**,包含您告訴我們的每個** 3模型**的屬性。 – Rostech

回答

1

使ViewModel然後發送ViewModel設置屬性後查看;設置@model ViewModel

public class MyModel1 {} 

    public class MyModel2 {} 


    public class ViewModel 
    { 
    public MyModel1 MyModel1 {get; set;} 
    public MyModel2 MyModel2 {get; set;} 
    } 

然後在你的view你可以使用你想要像@Model.MyModel1任何子模型等

+0

你會把ViewModel函數和它上面的代碼放在什麼類中? – Andre

0

如果你想在一個視圖中使用3種型號,您必須聲明一個「包」視圖模型包裝你想要使用的所有子模型。

首先,如果你必須創建你的子模型,如果你還沒有,那麼你將它們包含在包視圖模型中。

public class FirstViewModel 
    { 
     public int MyProperty { get; set; } 
    } 

    public class SecondViewModel 
    { 
     public string MySecondProperty { get; set; } 
    } 

    public class ThirdViewModel 
    { 
     public DateTime MyThirdProperty { get; set; } 
    } 

    public class BagViewModel 
    { 
     public FirstViewModel FirstModel { get; set; } 

     public SecondViewModel SecondModel { get; set; } 

     public ThirdViewModel ThirdModel{ get; set; } 
    } 

子模型可以是視圖模型或綁定模型。

而在你的Razor視圖,您包括BagViewModel:

@model BagViewModel 

然後,如果你想使用FirstViewModel(例如),你做到這一點:

@Model.FirstViewModel 
+0

我在html.beginform中編寫HTML.TextAreaBox(a => a.FirstModelName)時在搜索表單中做了這件事,它顯示了錯誤。 – akjjain91

+0

根據示例,您是否使用: - @ Html.TextAreaBox(model => model.FirstModel.MyProperty) 或者您確實使用 - @ Html.TextAreaBox(model => model.MyProperty)? – flacko

相關問題