簡體   English   中英

在MVC視圖之間傳遞參數以匹配模型中可用數據源中的項

[英]Passing arguments between MVC views to match an item from a data source available in the model

我有一個呈現內容頁面側欄的視圖。 側欄可以在單個頁面上渲染多次。 頁面的布局定義了幾個內容區段(或位置 ,在Kooboo的術語),這是,在實際的頁,綁定到特定視圖。 在每個此類視圖中,我都需要通過重新設置通用側欄視圖來選擇性地渲染側欄。

側欄的內容存儲在Kooboos數據庫中。 我正在使用一種特定的內容類型,為簡單起見,它具有以下兩個字段:

  • Position —頁面中位置的ID,與布局中定義的位置的ID相匹配
  • Content -構成側邊欄實際內容的HTML片段

側欄視圖的邏輯應如下:從綁定到當前頁面的所有側欄數據中,選擇一個Position與從外部視圖傳遞的Position相匹配的位置作為參數的單個項目,如果找到,則將其渲染。 問題是,我想不出一種將參數傳遞給視圖的方法

示例布局片段:

<!-- Header section -->
<section>
    <div class="section-content">
        @Html.FrontHtml().Position("Header")
        @Html.FrontHtml().Position("HeaderSectionContent")
    </div>
</section>

<!-- Main section -->
<section class="even">
    <div class="section-content">
        @Html.FrontHtml().Position("MainSectionContent")
    </div>
</section>

綁定到Header位置的示例視圖:

<div class="header-container">
    <h1 class="page-title" @ViewHelper.Edit(ViewBag.Solution, "Title")>
        @ViewBag.Solution.Title
    </h1>

    <!-- How to pass "Header" string as an argument into the Controls.Sidebar view? -->
    @Html.FrontHtml().RenderView("Controls.Sidebar",ViewData)

    <h2 @ViewHelper.Edit(ViewBag.Solution, "Perex")>
        @Html.Raw(ViewBag.Solution.Perex)
    </h2>
</div>

預期的通用側欄視圖Controls.Sidebar

@if (ViewBag.Sidebars != null) 
{
    // How to retrieve an argument and select the matching side bar data?
    var sidebar = ViewBag.Sidebars ... ;
    if (sidebar != null)
    {
        <div class="side-bar">
            <h3>@item.Title</h3>
            @Html.Raw(item.Content)
        </div>
    }   
}

最終,我需要能夠多次渲染該視圖,並有條件地渲染幾個有關數據可用性的側欄。

我一直在研究視圖編輯器中可用的Parameters定義,但似乎這提供了對查詢字符串參數的訪問,這不是我可以(希望)利用的機制。 Kooboo文檔缺少與此主題相關的任何信息。

在Kooboo中,至少有兩種方法可以將某些參數從一個視圖傳遞到另一個視圖:

首先,您可以將參數值存儲在父視圖中,如下所示:

    Context.Items["ParameterName"]=value;

或像這樣:

    var customViewData = new ViewDataDictionary();
    customViewData.Add("ParameterName", value);

然后,您可以調用子視圖的渲染:

    @Html.FrontHtml().RenderView("ChildViewName", ViewData) //a default ViewData passed

或分別如下:

    @Html.FrontHtml().RenderView("ChildViewName", customViewData)

在ChildViewName的接收端,您只需獲取參數值即可:

    var value = Context.Items["ParameterName"];

或因此分別:

    var value = ViewData["ParameterName"]; // NB: don't forget to cast parameter to a proper data-type, because ViewData is not processed same smoothly as ViewBag would. 

兩種方法都可以達到此目的。

暫無
暫無

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

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