2つの部分的なheader.cshtmlとfooter.cshtmlを含むtemplate.cshtmlを作成しました。複数のテンプレートをRazorEngineと別のビューモデルで使用する
それがレンダリングされると、それは次のようになります。
IRazorEngineService service = RazorEngine.Engine.Razor;
string _webPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "views");
var config = new TemplateServiceConfiguration
{
//Use this template manager when loading from template files.
TemplateManager = new ResolvePathTemplateManager(new[] { _webPath })
};
service = RazorEngineService.Create(config);
ITemplateKey key = service.GetKey("template");
service.Compile("header", typeof(HeaderViewModel));
service.Compile("footer", typeof(FooterViewModel));
var model = new ContentViewModel();
model.Content = "This is the content";
model.FooterViewModel = new FooterViewModel();
model.HeaderViewModel = new HeaderViewModel();
model.FooterViewModel.Footer = "footer";
model.HeaderViewModel.Header = "header";
var html = service.RunCompile(key, model.GetType(), model);
template.cshtml
@model RazorMachineTest.ContentViewModel
<html>
<body>
<header>
@Include("header", @Model.HeaderViewModel, typeof(RazorMachineTest.HeaderViewModel))
</header>
<h1>@Model.Content</h1>
<footer>
@Include("footer", @Model.FooterViewModel, typeof(RazorMachineTest.FooterViewModel))
</footer>
</body>
</html>
header.cshtml
私は解決策については好きではない何footer.cshtml
@using RazorEngine
@using RazorMachineTest
<b>I am inside the </b>
<span>@Model.Footer</span>
はのviewmodelsが互いの中に含まれていなければならないということです。
私はそれぞれのビューモデルの分離をしたいと思います。他のものを知るべきではありません。その理由は、コンテンツが一般的なヘッダーまたはフッターを知っているべきではなく、一般的なヘッダー/フッターの親であってはならないからです。
多くの異なる「コンテンツ」ビューモデルでテンプレートを再利用したいからです。
私の既存のコードに基づいてこの作業を行うためには、正確に何を変更する必要がありますか?
注:RazorMachine名前空間を読めばドンの `tは
あなたは既に '@これだけ別の場所に保管してくださいinclude'でモデルを与えているViewBag.Header @でviewbagにアクセスすることができますモデルは入っていませんか? –
インクルードを呼び出してモデルを同じ時間に渡すことはできますか?サンプルコードをお願いしますか? – HelloWorld
あなたは他の場所からモデルを渡します。それはあなたがビューに与える同じモデルの中にある必要はありません。あるいは、3つのモデルをカプセル化したシンプルなモデルを常に押して、別々にすることもできます。 –