簡體   English   中英

許多模型可以查看許多部分視圖

[英]Many models to view with many partial views

我有一個包含許多部分視圖的視圖,我需要將匹配的模型傳遞給每個視圖。

我找到了兩種方法來做到這一點,但我不知道它應該采取什么樣的方式。

  1. 我想創建包含所有模型作為屬性的大類,而不是將模型發送到每個局部視圖。 問題是它的硬打字,如果我需要通過不同的模型組合,它不適合。

  2. 我的另一種方法是在每個模型中有一個方法,為每個局部視圖(GetMenuBar()等提供模型)。

這樣做的正確方法是什么?

我的建議,與選項1一起使用。我在所有主視圖/多部分視圖方案中使用它。 它很容易維護,因為每個部分都擁有自己的ViewModel。 它使整個事物保持干凈整潔

我使用完全相同的設置,如下所示:

public class MainViewModel {

    public Partial1ViewModel Partial1 [ get; set; }
    public Partial2ViewModel Partial2 [ get; set; }
    public Partial3ViewModel Partial3 { get; set; }
    public Partial4ViewModel Partial4 { get; set; }

    public MainViewModel() {}

    public MainViewModel() {
        Partial1 = new Partial1ViewModel();
        Partial2 = new Partial2ViewModel();
        Partial3 = new Partial3ViewModel();
        Partial4 = new Partial4ViewModel();
    }
}

每個PartialViewXViewModel都是它自己的ViewModel,如果需要,可以在另一個視圖中重用。

渲染的動作可能如下所示:

public ActionResult Index {
    var model = new MainViewModel();
    return View(model);
}

你的觀點

@model MainViewModel

<div>
    {@Html.RenderPartial("PartialOne", Model.Partial1)}
</div>


<div>
    {@Html.RenderPartial("PartialTwo", Model.Partial2)}
</div>


<div>
    {@Html.RenderPartial("PartialThree", Model.Partial3)}
</div>


<div>
    {@Html.RenderPartial("PartialFour", Model.Partial4)}
</div>

為每個PartialX定義UI,如:

@model Partial1ViewModel

//view html here

現在,每個部分視圖html和他們使用的每個模型都可以在任何地方使用。

現在最重要的是,如果你有一個頁面只需要其中的2個,你只需要創建一個新的ViewModel來表示特定的視圖,如下所示:

public class OtherMainViewModel {

    public Partial2ViewModel Partial2 [ get; set; }
    public Partial4ViewModel Partial4 { get; set; }

    public OtherMainViewModel() {}

    public OtherMainViewModel() {
        Partial2 = new Partial2ViewModel();
        Partial4 = new Partial4ViewModel();
    }
}

並在另一個視圖中使用它:

public ActionResult SomeOtherAction {
    var model = new OtherMainViewModel();
    return View(model);
}

這是完全可以接受的,也是MVC中首選的設計策略,使ViewModel能夠專門代表視圖需要的內容以及它所需要的內容。

您可能希望使用不同的方法來填充模型。 大多數人會建議使用Automapper。 無論哪種方式,上面只是在MainViewModel的構造函數中初始化PartialViewXModel。 如果您使用數據庫中的數據填充這些模型,則不一定是您的情況。 你會想要自己的策略。 這可以在這里工作:

public ActionResult Index {
    var model = new MainViewModel();
    model.Partial1 = GetPartial1Data(); // this method would return Partial1ViewModel instance
    model.Partial2 = GetPartial2Data(); // same as above for Partial2ViewModel
    ...
    return View(model);
}

這一切都只是讓你開始設計,你可以調整它的心臟內容:-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM