我有一个 Knockout js viewModel 并希望使用外部模板来获取 MVC 4 razor (cshtml) 绑定页面,因此可以在服务器上创建初始页面或通过 Knockout 绑定,我将在运行时决定。我想像这样将模板的名称传递给控制器(/Templates/KnockoutTemplate?templateName='gauge'),其中“gauge”是视图的名称(radial.tmpl.cshtml),并让 Knockout 将其放入模板块。
我的控制器:
public class TemplatesController : Controller
{
public TemplatesViewModel viewModel { get; set; }
public TemplatesController()
{
this.viewModel = new TemplatesViewModel { Heading = "Radial" };
}
public ActionResult KnockoutTemplate(string templateName)
{
// is this right?
return PartialView(templateName, this.viewModel);
}
}
径向.cshtml
@model MVC4.Models.TemplatesViewModel
@{
ViewBag.Title = "Radial Template";
}
<div id="radialDashboardWidget" class="dashboardWidget" style="width: 100%">
<h4 class="bold">@Model.Heading </h4>
<!-- or I can do this, I'll decide at development time -->
<h4 class="bold" data-bind="text:heading"></h4>
</div>
主页
<div id="dashboardWidgets" data-bind="foreach: Widgets" class="flexible-widget">
<!-- ko template: {name: Properties.templateName } -->
<!-- /ko -->
<div class="clear" />
</div>