I have a Knockout js viewModel and want to use external templates to get an MVC 4 razor (cshtml) bound page so the initial page can be created on the server or bound through Knockout, I’ll decide at runtime. I want to pass the name of the template to the controller like this (/Templates/KnockoutTemplate?templateName=’gauge’) where ‘gauge’ is the name of a view (radial.tmpl.cshtml) and have Knockout put it in the template block.
My Controller:
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);
}
}
radial.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>
main page
<div id="dashboardWidgets" data-bind="foreach: Widgets" class="flexible-widget">
<!-- ko template: {name: Properties.templateName } -->
<!-- /ko -->
<div class="clear" />
</div>
I’ve answered this here: http://geekswithblogs.net/Aligned/archive/2012/08/17/knockout-js-and-external-mvc-cshtml-templates.aspx
My Controller:
radial.cshtml
Dashboard page with Knockout