Asp.net-Mvc
如何將 HTML 內容傳遞給 MVC-Razor 中的部分視圖,如“for”塊
我在我的應用程序中使用 Chromatron 主題作為管理面板。有一個帶有 HTML 內容的側邊欄小工具,通過一點 CSS 技巧,它可以顯示完全不同的內容。
<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(...){ }。這在 Razor 中可行嗎?
我也有同樣的困境。嘗試使用 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)如果您想花哨,可以添加此擴展方法。
public static class PartialExtensions { public static IHtmlString Display<T> (this T model, Expression<Func<T, Func<Object, IHtmlString>>> content) { var compiled = content.Compile(); return compiled.Invoke(model).Invoke(null); } }然後,任何時候你使用這個模式,你都可以在你的部分(未完全測試)中這樣呼叫它。
@model ContainerViewModel @Model.Display(m => m.Content) // Use delegate property希望這對你有用。
它之所以有效,是因為 @… 語法為您創建了一個小 HtmlHelper,它使用一個 Model(您在此處將其聲明為 type
object並傳遞null),並返回一個IHtmlString.如果在內容中使用了@Html.BeginForm,請注意表單值似乎不會發佈到伺服器。
因此,將表單包裹在容器周圍。