2012-03-06 48 views
9

我在我的應用程序中使用Chromatron主題作爲管理面板。有一個側邊欄小工具,它具有HTML內容,並有一點CSS技巧,可以顯示完全不同。如何將HTML內容傳遞到MVC-Razor中的部分視圖,如「for」塊

<section class="sidebar nested"> 
    <h2>Nested Section</h2> 
    <p>Lorem ipsum dolor sit amet, conse ctetur adipiscing elit. Maec enas id augue ac metu aliquam.</p> 
    <p>Sed pharetra placerat est suscipit sagittis. Phasellus <a href="#">aliquam</a> males uada blandit. Donec adipiscing sem erat.</p> 
</section> 

我想有一個部分認爲這樣使用:

@Html.Partial("Path/To/Partial/View"){ 
    <h2>Nested Section</h2> 
    <p>Lorem ipsum dolor sit amet, conse ctetur adipiscing elit. Maec enas id augue ac metu aliquam.</p> 
    <p>Sed pharetra placerat est suscipit sagittis. Phasellus <a href="#">aliquam</a> males uada blandit. Donec adipiscing sem erat.</p> 
} 

TBH,我想有功能,例如我有一個@for(...){ }塊。 這可能在剃刀嗎?

+1

我不知道這是你想要的,但看看:http://lostechies.com/hugobonacci/2011/07/11/templates-with-razor/ – 2012-03-06 17:58:10

+0

謝謝Felipe。但這不是我正在尋找的東西,或者我可能無法使其工作。我需要與'for'塊相同的功能。我想有一個尾部塊,可以插入其他'@'razor指令或HTML內容;完全像'for'塊... – Achilles 2012-03-07 11:07:26

+0

我正在嘗試做同樣的事情;看到我的[*非常相似* SO問題](http://stackoverflow.com/q/21760850/173497)。我發現的最接近的是@FelipeOriani提到的帖子。 'HtmlHelper'擴展方法也可以工作,但我還沒有想出將它用作視圖或局部視圖的HTML存儲。但是,實際上,我只是放棄了輔助函數語法的括號語法。 – 2014-02-21 19:20:53

回答

15

我有同樣的困境。嘗試使用Func屬性創建視圖模型類型,然後將html作爲委託來傳遞。

public class ContainerViewModel 
{ 
    public String Caption { get; set; } 
    public String Name { get; set; } 
    public Int32 Width { get; set; } 
    public Func<object, IHtmlString> Content { get; set; } 
} 

@Html.Partial("Container", new ContainerViewModel() 
{ 
    Name = "test", 
    Caption = "Test container", 
    Content = 
    @<text> 
     <h1>Hello World</h1> 
    </text>, 
    Width = 600 
}) 

你可以在你的部分中這樣稱呼它。

@Model.Content(null) 

希望這適用於你。

它的工作原理,因爲@ ...語法創建一個小的HtmlHelper你消耗模型(你正在聲明這裏object型,並通過null的),並返回一個IHtmlString

如果在內容中使用@ Html.BeginForm,請注意表單值不會發布到服務器。

因此,將您的表單包裝在容器周圍。

+1

我喜歡這個解決方案,但<動態,...感覺真的很髒,所以我做了一些戳。事實證明,你正在創建一個隱含的HtmlHelper,它需要一個Model,所以輸入到Func的參數的類型是你喜歡的任何東西(如果你想要的話),並且返回類型總是IHtmlString。編輯答案反映了這一點。完美的作品! – 2014-08-02 03:45:06

+0

這個解決方案絕對精彩!我可以用周圍的HTML內容創建我的小部件/部分,並使用此方法在其中注入內容。它很乾淨,工作得很好!謝謝! – 2016-08-29 11:20:26

0

看起來你想要某種類型的htmlhelper函數來生成該內容。你有沒有考慮過將它作爲幫手而不是局部視圖來實現?

+0

我已經研究過「內聯助手」,它完成了這項工作;實際上有幾種方法可以將內容傳遞給佔位者;但我認爲如果我可以使用上面顯示的符號這樣的符號,我的HTML代碼將更加清晰。 – Achilles 2012-03-30 20:56:48

相關問題