簡體   English   中英

我怎樣才能調用一個 Action 和 output 它的結果,就好像它是一個“用戶控件”一樣?

[英]How can I invoke an Action and output it's result, as if it were a "user control"?

在我的_Layout.cshtml文件中,我想調用如下內容:

    <div id="content">
        <div id="left-wrapper" class="box">
            @Html.Action("FreeThisWeek", "Products")
            @RenderBody()
        </div>
    </div>

這是我的 ProductsController 文件:

[ChildActionOnly]
public ActionResult FreeThisWeek()
{
    //Some code that fetches the data and builds the model.
    var model = BuildFreeProducts();
    return View(model);
}

如果我嘗試運行這段代碼,我會得到一個StackOverflowException ,因為 Action 返回請求 Layout 的 View(),它運行返回 View() 的 Action,等等。

可以理解,但是我該如何完成這個正確的代碼呢?

我在哪里編寫將此數據 model 與我編寫的 HTML 組合在一起的視圖?

嘗試返回PartialView("yourview",model) 確保您返回的視圖不使用此頁面作為布局。 您可以通過在要返回的視圖頂部使用@{Layout=null}來指定它。

您將在FreeThisWeek操作中返回視圖,並在視圖中再次使用 _Layout。 所以它變成了遞歸。

Go 到您的FreeThisWeek視圖並將布局設置為 null

@{
   Layout=null;
}

暫無
暫無

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

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