Data Moving Plug-in SPA View Engine

Data Moving Plug-in SPA View Engine: Handling Contextual Information and User Authorization


The RTM version of the Data Moving Plug-in comes with a sophisticated SPA view engine. Views are downloaded dynamically from the server when they are needed together with Javascript AMD modules containing all code they need to work properly.

Views are developed as Mvc Partial Views and are then compiled into client side templates. Accordingly, they may use all Data Moving Plug-in controls and features

Also the AMD associated with each View may be developed as Partial Views and may take advantage of the Razor syntax to supply dynamic content to the client. Specifically, the developer may use Html extensions to serialize .Net data structures into their equivalent Javascript data structures, thus avoiding the duplication of the same data structures in both .Net and javascript. Moreover, the AMD content may depend on the language selected and on the user logged – in, and in general it may depend on contextual information, since it is created dynamically.

Both Views and their associated AMD are deployed by Asp.Net Mvc  Controllers that take care of verifying user authorizations, of minifying the AMD code, and of handling the caching of both Views and AMD.


Views are organized into logical units, in the same way as several classes are organized into dlls (dynamic load libraries). In turn, each logical unit  is composed of two deployment units: a template module containing all Views of the logical unit compiled into clients templates, and an overall AMD module containing the Javascript code associated with all Views of the template module in a minified format. Thus, Mvc Controllers, actually deploy template modules and overall AMD modules.

The organization of Views and of  their associated AMD modules into deployment units increases the modularity of the application and reduces server round trips.

Typically all View related modules are deployed by an unique Controller that has a different action method for each module. In other words each action method is in charge for deploying both the overall  AMD and the template module of a single logical unit.

Below a typical action method:

  1. public ActionResult Home(bool isJs)
  2. {
  3.     string module = "Home/Main";
  4.     if (isJs) return this.MinifiedJavascriptResult(module+"Js");
  5.     return PartialView(module, "Home");
  6. }


If the isJs  parameter is true the controller deploys the overall AMD module, otherwise it deploys the template module. The overall AMD module is deployed by the MinifiedJavascripResult method that takes care of extracting and minifying all javascript contained in the partial View.

In the example above the template module, and the overall AMD module are contained respectively in the partial views Home/Main.cshtml, and Home/MainJs.cshtml located under the controller folder. Both files don’t contain the whole code but just the code needed to package all Views and all AMD modules into single deployment units. Typically, the code of each view and AMD is contained in a separate partial view that is called by the Main or MainJs partial view.

Below a typical organization of Views and AMD files handled by a controller called TemplatesController:

SPA Views AMDs

Each logical unit is contained in a folder with the same name of the unit. All partial views containing code have the same name of their associated Views with a Js postfix. The Main and MainJs partial views of each folder take care of packaging all partial views contained in the folder into the two deployment units called by the controller.

Below a typical MainJs module:

  2. <script>
  3.     define(function () {
  4.         @Html.IncludeStaticJsModules("Home/MenuJs", "Home/RegisterJs",
  5.                                   "Home/LoginJs", "Home/LogoutJs", "Home/RegistredJs")
  6.         return mvcct.core.withIncludedModules(
  7.             function (menuF, registerF, loginF, logoutF, registredF) {
  8.                 return function (vm, viewName) {
  9.                     if (viewName == "Menu") return menuF(vm);
  10.                     else if (viewName == "Register") return registerF(vm);
  11.                     else if (viewName == "Login") return loginF(vm);
  12.                     else if (viewName == "Logout") return logoutF(vm);
  13.                     else if (viewName == "Registred") return registredF(vm);
  14.                     return null;
  15.             }
  16.         });
  17.     });
  19. </script>


It is an AMD that returns a function of two parameters a data item and a view name. This function will be called with the name of the view to render and with the data item that will be bound to that view. This function just selects a function specific for each view that is defined in a separate partial view. The javascript code in the partial view must be included within <script> tags to get a valid Razor syntax. These tags will be removed by the MinifiedJavascriptResult helper method in the controller.

The partial views containing the view specific javascript code are included statically in the MainJs partial view with the call to  @Html.IncludeStaticJsModules. After that , the javascript mvcc.core.withIncludedModules binds the values returned by all view specific modules to the parameters, menuF, registerF,…etc.The structure of a typical view specific module will be descibed later on in this post.

Below also a typical Main partial view:

  1. @model System.String
  2. @using SPAExample.Models
  3. @{var toRender = Html.DeclareClientTemplates(Model)
  4.       .AddContentPagePartial<FatherVirtualReferenceMenuItem>( "Home/Menu", null, "Menu")
  5.       .AddContentPagePartial<LoginModel>("Home/Login", null, "Login")
  6.       .AddContentPagePartial<LoginModel>("Home/Logout", null, "Logout")
  7.       .AddContentPagePartial<LoginModel>("Home/Registred", null, "Registred")
  8.       .AddContentPagePartial<Person>(
  9.       "Home/Register", null, "Register")
  10.       .AddPartial<VirtualReferenceMenuItem>("Home/MenuItem", null, "MenuItem");
  11.   }
  12. @toRender.Render()


It receives as input the module name. In fact the module name is not fixed, but may contain prefixes with the selected language, the user logged in, and other context-dependent information. Thus, in general, a module name has a structure of the type: en-US/john777/Home.  The code contained in the view declares the module, adds a template for each view, and finally renders the whole module The rendered content is an Html node containing several client side template inside it. The first argument of each template declaration is the template, while the last argument is the view local name; the view full name is obtained as: <module name>+”_”+<view local name>. In the example above  each template is specified with a partial view, so the first argument is just the partial view name. However, templates may be specified also as in-line razor templates. See here fore more details on templates.

The AddContentPagePartial helper  is a simplified way to define Views that cover the role of virtual pages. In fact each virtual page has the following standard structure:

  1. public class baseViewModel<T>
  2. {
  3.     public T Content { get; set; }
  4.     public string view { get; set; }
  5.     public string module { get; set; }
  6.     public bool hasJs { get; set; }
  7. }


It contains the view local name, the module the view is in (without any contextual prefix), a boolean that is true if the page has associated javascript code. Then it contains a generic content. The AddContentPagePartial helper specifies a template for just the content of the page.

Below the two routing rules that pass all AMD and template modules requests to the action methods:

  1. routes.MapRoute(
  2.     name: "Templates",
  3.     url: "templates/{action}/",
  4.     defaults:
  5.         new { controller = "Templates", action = "Home", isJs =  false}
  6. );
  7. routes.MapRoute(
  8.     name: "templatesAMD",
  9.     url: "templates_amd/{action}.js",
  10.     defaults:
  11.         new { controller = "Templates", action = "Home", isJs = true }
  12. );


Below the action method that deploys the “People” template module and overall AMD only to logged users:

  1. public ActionResult People(string user, bool isJs, string ticket)
  2. {
  3.     string module = "People/Main";
  4.     if (!SPASecurity.ValidateUser(user, ticket)) return new HttpUnauthorizedResult();
  5.     if (isJs) return this.MinifiedJavascriptResult(module + "Js");
  6.     return PartialView(module, user+"/People");
  7. }


It has two more parameters: the user name, and the authentication ticket. In the template module request the authentication ticket is passed in the asp.net authentication cookie, while in the overall AMD request the ticket is inserted in the query string with the format: ?ticket=<auth ticket>, since Javascript file requests typically do not send cookies.
The SPASecurity.ValidateUser static method verifes the authentication ticket, and returns an HttpUnauthorizedResult when the verification fails.
The username is explicitly inserted in the URL  so that both template and javascript files may be cached on a user dependent way. In general, context information like the username and the language selected are stacked before the module name in the URL:
../en-US/john122/People.js?ticket=<auth ticket>, and …../en-US/john122/People/.
URLs are built automatically this way  on the client side according to context rules provided by the developer.  We will discuss these rules in the next post about the SPA engine.
The routing rules for all user dependent modules are :

  1. routes.MapRoute(
  2.     name: "TemplatesWithUer",
  3.     url: "templates/{user}/{action}/",
  4.     defaults:
  5.         new { controller = "Templates", action = "Home", isJs = false}
  6. );
  7. routes.MapRoute(
  8.     name: "templatesAMDWithUer",
  9.     url: "templates_amd/{user}/{action}.js",
  10.     defaults:
  11.         new { controller = "Templates", action = "Home", isJs = true }
  12. );


Modules are cached by the browser if we add adequate OutputCache attributes to the action methods that handle the modules. However modules are cached also inside the Html page with a least recently used strategy to improve performance. As a default the framework cache 10 modules, but this value may be changed by calling the javascript method:

  1. mvcct.ko.dynamicTemplates.cache(<cache size>);

The View Engine Cycle

Views are loaded in “placeholders” bound to  model properties: each time the a new data item is inserted in the property, a template selection function selects a new view to use for rendering the new data item. Before rendering starts the data item is manipulated, and possibly filled with new content by the AMD associated with the selected view.

More specifically, the following procedure is triggered each time a new data item vm is associated to a “placeholder”:

  1. A template selection function selects the view to render.
  2. If the module the View belongs to has not been downloaded from the server, yet, it is downloaded.
  3. A function func returned as value from the AMD associated with the view is evaluated on the data item, and on the view name: func(vm, viewName).
  4. The result res returned by the function evaluation is possibly stored in a property of the data item, and is used also in the last step of this procedure.
  5. The selected view (which is a client template) is instantiated , bound to the data item using knockout bindings, and inserted in the “placeholder”.
  6. if res contains a property called afterRender, it is assumed to be a function that is evaluated passing it the array of html nodes created by the view instantiation, and the data item vm.


Thus, the developer may modify vm before its rendering with func and immediately after its rendering with the afterRender function. Typically, func fills vm with javascript content while afterRender applies jquery plugins to the rendered content, and specifies options of updatesManagers and retrievalManagers possibly created during the view rendering.

Typically, data items, representing “virtual pages” are initially empty, and contain just the page complete name (module name + view name). The whole page content is put in place by func. The function func is the same for each module and it is the function returned by each MainJs partial view, we discussed before in this post. It just dispatches the call to view specific functions. Below a view specific javascript module that prepares a menu virtual page:

  1. @{
  2.         var menuItems = new List<BaseVirtualReferenceMenuItem>();
  3.         var menuItem = new VirtualReferenceMenuItem(
  4.             new virtualReference() { module = "Home", view = "Login", },
  5.             SiteResources.LinkToLoginText, SiteResources.LoginTitle);
  6.         menuItems.Add(menuItem);
  7.         menuItem = new VirtualReferenceMenuItem(
  8.             new virtualReference() { module = "Home", view = "Register", },
  9.             SiteResources.LinkToRegisterText,
  10.             SiteResources.RegisterTitle);
  11.         menuItems.Add(menuItem);  
  12.         menuItem = new VirtualReferenceMenuItem(
  13.             new virtualReference() { module = "People", view = "List", },
  14.             SiteResources.LinkToHumanResourcesListText,
  15.             SiteResources.HumanResourcesListTitle);
  16.         menuItems.Add(menuItem);
  17.         var mainMenu = new FatherVirtualReferenceMenuItem()
  18.         {
  19.             Children = menuItems
  20.         };
  21.     }
  23.    <script>
  24.     (function () {
  25.         @Html.JavaScriptDefine("mainMenu",  mainMenu)
  26.         mvcct.core.moduleResult(function (vm) {
  27.             if (!vm._initialized) {
  28.                 vm._initialized = true;
  29.                 vm.Content = ko.mapping.fromJS(mainMenu);
  30.                 vm._title = "@SiteResources.HomeTitle";
  31.             }
  32.             return null;
  33.         });
  34.     })();  
  35. </script>

The data structure containing all menu information is built in .Net with the help of the virtualReference class that defines virtual links to virtual pages. Text content is taken from a resource file, so it may depend on the selected language. The VirtualPageMenuItem class is not part of the Data Moving Plug-in, but is specific of the example.

The .Net data structure is serialized in javascript by the JavascriptDefine helper that defines a javascript variable named mainMenu and fills it with the serialized data structure.

The mvcct.core.moduleResult javascript funtion returns the module result to the calling MainJs AMD. The returned value is the function that will be applied to the data item vm in case the view required is a “Menu” view. If vm has not been already initialized this function fills the Content property of the virtual page with the data structure describing the whole menu.

Below a javascript module that uses an afterRender function to apply a jQuery plugin to the submit button:

  1.    <script>
  2.     (function () {
  3.         @Html.JavaScriptDefine("personForm", new Person() )
  4.         var afterRender = function (nodes, vm) {
  5.             var root = $(mvcct.core.filterHtml(nodes));
  6.             if (root.length == 0) return;
  7.             var prefix = root.attr("data-helper-prefix");
  9.             $('#' + prefix + "_btnSubmit").button().click(function () {
  10.                 var form = $(this).closest('form');
  11.                 if (form.validate().form()) vm.updater.update(form);
  12.             });
  13.         }
  14.         mvcct.core.moduleResult(function (vm) {
  15.             if (!vm._initialized) {
  16.                 vm._initialized = true;
  17.                 ...
  18.                 ...
  19.                 ...
  20.                 ...
  21.             }
  22.             return {afterRender: afterRender };
  23.         });
  24.     })();  
  25. </script>


It is worth to point out how the button is located in the page. We can’t use a Css class to locate the button since this way we would risk to re-apply the jquery plug-in also to other buttons contained in other instances of the same view that have already been rendered in the Html page. A .find applied only to the newly created content might be too inefficient since it would not use CSS inedexes of the Html page.  Thus, the best solution is using ids and Css classes that are specific to the instance of the view. In our case we prefix the button id with an unique identifiers, different for each view instance, with the PrefixedId helper:

  1. <input id="@Html.PrefixedId("btnSubmit")"
  2.         type="button" value="@SiteResources.Submit" class ="button"/>


The same prefix is added in the data-helper-prefix html5 attribute of the root node of the template:

  1. <div class="@(JQueryUICssClasses.ContentContainer+" main-page")"
  2.     data-helper-prefix="@Html.PrefixedId("")">


This way the javascript module may read the prefix that uniquely identifies the page instance with:

  1. var prefix = root.attr("data-helper-prefix");


and it may use it to locate all html content in the view instance. The root html node is computed by filtering out all not-Html nodes from the array of all rendered nodes with the helper function: mvcct.core.filterHtml.

The content of each AMD, may depend on parameters like the selected language, or the user logged in, but it can’t depend on the specific database state since, for performance reasons,  AMD module must be cached by the browser. Therefore, data coming from the database can’t be added to  vm by func, that is part of an AMD, but must be required to the server with a subsequent ajax call placed in the afterRender function or by instructing a retrievalManager to fetch data from the server as soon as it has been created.

Below a retrievalManager instructed to fetch data from the server immediately after it has been created:

  1. .StartAjaxPostRetrievalManager(true,
  2.     "@._utilities.humanResourcesRM",
  3.     1, actionUrl: Url.Action("JsonQuery", "HumanResources"))


It is enough to set to true the first parameter passed to the retrievalManager.

The javascript module associated to the view of the retrievalManager above, specifies some options for the retrievalManager and for an updatesManager rendered in the view in its afterRender:

  1.    <script>
  2.     (function () {
  3.         @Html.JavaScriptDefine("viewModel",  new HumanResourcesViewModel())
  4.         function afterRender(nodes, vm) {
  5.             vm.updater.options({
  6.                 onUpdateComplete: function () {
  7.                     $.unblockUI();
  8.                 },
  9.                 htmlStatusMessages: function (statusCode, statusText) {
  10.                     if (statusCode == 401) return "@SiteResources.Unauthorized";
  11.                     else return statusText;
  12.                 },
  13.                 updatingCallback: function () {
  14.                     $.blockUI();
  15.                     return true;
  16.                 }
  17.             });
  18.             vm._utilities.humanResourcesRM.options({
  19.                 htmlStatusMessages: function (statusCode, statusText) {
  20.                     if (statusCode == 401) return "@SiteResources.Unauthorized";
  21.                     else return statusText;
  22.                 }
  23.             });
  24.         }
  25.         mvcct.core.moduleResult(function (vm) {
  26.             if (!vm._initialized) {
  27.                 ...
  28.                 ...
  29.                 ...
  30.             }
  31.             return { afterRender: afterRender };
  32.         });
  33.     })();  
  34. </script>


The options passed specify custom error messages in case of unauthorized access to the server methods (status code 401), and apply screen blocking during the communication with the server.

Defining the View Placeholders

Views are loaded into View placeholder, that are bound to model properties. Root placeholders are inserted in the host Html page and each view may,  in turn, contain nested view placeholders. Views inserted in root placeholders play the role of virtual pages, while nested views play the role of “widgets”. A physical Html host page may contain several virtual pages, but most of SPA contain just a single root view placeholder that is connected with the back and forward browser buttons to simulate the behavior of a standard Html page.

Root placeholder are defined with the ClientIteratorFor helper extension. Below an example of usage:

  1. <div class="page-container">
  2.     @h.ClientTreeIteratorFor(m => m.CurrentPage, null,
  3.       "function(x){ $(mvcct.core.filterHtml(x)).fadeOut(0).fadeIn(500);}",
  4.       "function(x, y, i, f){$.when($(mvcct.core.filterHtml(x)).fadeOut(500)).always(f);}")
  5. </div>


The first parameter is the property that will be bound to the view placeholder. Each time a new data item is inserted in this property the view engine cycle is run to load a new view. In SPA applications the second parameter is always null, while the third and fourth parameters specify respectively a before render and an after render functions. They are used to implement transition animations. In the example above the before render function runs a fade-out animation, while the after render function specifies a fade-in animation. When the before render animation completes it MUST call the function f passed as fourth parameter to inform the view engine that it can remove the old view and can insert the new one.

Placeholders for nested views are specified with RecurIterationOnSingle and RecurIterationOn html extensions. The first one adds a single view instance and may be bound to a property containing a single data item, while the second one adds several views, one for each data item contained in the IEnumerable it is bound to. Below a RecurIterationOnSingle renders a widget containing a page header and a RecurIterationOn helper renders all menu item of a menu page:

  1. <div class="@(JQueryUICssClasses.ContentContainer+" main-page")">
  2.     <h1 class="@(JQueryUICssClasses.HeaderContainer+" main-menu-title")">
  3.             @SiteResources.HomeTitle</h1>
  5.     @Html.RecurIterationOnSingle(m => m.Header,
  6.         wrapper: ExternalContainerType.div, wrapperAttributes:
  7.             new {data_spa_widget="Basic.NavigationHeader.js", @class="header-links"})
  9.     @Html.RecurIterationOn(m => m.Children,
  10.         wrapper: ExternalContainerType.nav, wrapperAttributes:
  11.             new {data_spa_widget="Home.MenuItem", @class="main-menu"})
  12. </div>


Their first parameter is the property the placeholder will be bound to, while the wrapper and wrapperAttributes optional parameters specify respectively an html node that will enclose the dynamic content and its Html attributes. The data-spa-widget html5 attribute specifies witch view to render. More details on the use of this attribute are contained in the next section.

Also the RecurIterationOnSingle and RecurIterationOn html extension allow before render and after render animations useful to define transition.

Virtual Pages and Default Template Selection Function

The view to load is decided by a template selection function. The default template selection function is able to select the view to load just for virtual pages and for widgets. Normally, this is enough, but the developer has also the option to specify a custom template selection function to be used for all nested views of a module, as first parameter of the Render function of the module definition:

  1. @{var toRender = Html.DeclareClientTemplates(Model)
  2.       ...
  3.       ...
  4.       ...
  5.   }
  6. @toRender.Render("$data.myCustomTemplateSelection")


The $data bindings variable specifies that the function is contained in the current view model. We may use also $parent, etc. For more details see here.

Virtual pages are data items that works as empty containers and that specify the view they “need” through their view, module, and hasJs properties, so the default template selection needs just to read these properties. The selected AMD module fill the Content property of the empty page with content specific for the selected view and transforms the empty page into a complete working page.

Nested views (views that are not virtual pages) may be selected by the default template selection functions by means of the data-spa-widget html5 attribute that may be placed in the wrapper Html node that encloses the view placeholder. Its format is: <module>.<view>[.js]. The js suffix specifies that the module has an associated AMD module.

Pages are handled by mvcct.ko.dynamicTemplates.pageStore instances. When the application starts a default pageStore instance is created  and inserted in the mvcct.ko.dynamicTemplates.defaultPageStore variable. The developer needs to create other pageStore instances only if the host page contains several page placeholders.

Pages are created by passing a virtualReference object to the get method of a pageStore instance. Once we receive the requested virtual page from the get method we may place it in a property associated with a virtual page placeholder. This trigger automatically the view loading procedure.

Below the first page loading that bootstraps an SPA:

  1. applicationModel.CurrentPage(mvcct.ko.dynamicTemplates.defaultPageStore.get(
  2.     new mvcct.ko.dynamicTemplates.virtualReference("Home", "Menu")));


If the stored property of the virtualReference is true (its default) the virtual page is stored in the page store after its creation, while if the stored property is true (its default) an already stored virtual page with the same full name will be returned, if available in the page store. The virtualReference may specify also a role string property. In this case a stored page is returned only if the role specified when it was created matches the role of the virtualReference passed to the get method.

After the SPA bootstrap a new page may be loaded passing a virtualReference directly to the goTo method of current page. If no second argument is passed the page is retrieved from the default page store, otherwise the second argument must be the page store to use. Most of the times, we don’t call directly the goTo method but use the VirtualLink and VirtualLinkFor html extensions that do this job for us:

  1. @Html.VirtualLinkFor(m => m.Text, m => m.Link, title: m => m.Title)


Where the Link property must contain an instance of the virtualReference class.

The main purpose of the page store is to keep the state of each page, so that when the user returns on the same page he finds the page exactly in the same state he left it. This ensures a better user experience, and makes the SPA similar to a native windows application.

A call to the enablePushState method of a pageStore instance connects it to the browser history, so the user may navigate among the virtual pages with the back and forward browser buttons. If the browser doesn’t support pushState, the view engine reverts automatically to a software simulation.

Static Modules

Some modules might be loaded immediately when the SPA starts. For instance it is convenient that widgets used by all pages, such as page headers and footers  be loaded as soon as the SPA starts and kept in the page for the whole lifetime of the page. The error page that is shown in case of module loading errors MUST be loaded statically when the SPA starts to ensure that it is always available in case of network problems.

Loading modules statically is straightforward. The AMD module is required with a standard javascript <script> tag:

  1. <script src="@Url.Content("~/templates_amd/Basic.js")" type="text/javascript"></script>


However, in this case the define instruction contained in the module MUST specify explicitly the module name:

  1. <script>
  2.     define("Basic", function () {
  3.         @Html.IncludeStaticJsModules("Basic/NavigationHeaderJs")
  4.         return mvcct.core.withIncludedModules(function (navigationHeaderF) {
  5.             return function (vm, viewName) {
  6.                 if (vm && viewName == "NavigationHeader") return navigationHeaderF(vm);
  7.                 return null;
  8.             }
  9.         });
  10.     });  
  11. </script>


The template module, instead, is defined inside the host page in exactly the same way it is defined in a Main.cshtml file:

  1. @{var errorTemplates = Html.DeclareClientTemplates("Basic")
  2.     ...
  3.     ...
  4.     ...
  5. }
  6. @errorTemplates.Render()


The Host Page

The host page must specify the following configuration information:

  1. Possible options of the AMD loader. The Data Moving Plug-in officially supports require.js, but other AMD loaders with the same interface should work as well.
  2. The base url where to download the template modules and the base url where to download the associated AMD modules
  3. Loader callbacks that block/unblock the screen during the module loading, and that specify which view to show in case of load errors.
  4. The template modules cache size, if different from the 10 default.
  5. Some pageStore configuration (typically just if the page store must be connected to the browser history)


Typically all this information is inserted in the page header as shown in the example below:

  1. @section Header{
  3.     <link href="~/Content/Site.css" rel="stylesheet" />
  4.     <script src="@Url.Content("~/Scripts/jquery.blockUI.min.js")" type="text/javascript"></script>
  6.   <script type="text/javascript">
  7.         var require = {
  8.             baseUrl: "@Url.Content("~/Scripts/Modules")",
  9.             waitSeconds: 10
  10.         };
  12.       @Html.JavaScriptDefine("viewModel",  new PageError())  
  13.       mvcct.ko.dynamicTemplates.callBacks({
  14.         onLoad: function () { $.blockUI(); },
  15.         onLoadEnd: function () { $.unblockUI(); },
  16.         onLoadFailed: function (module, nodes, data) {
  17.             data._errorPage = "Basic_defaultError";
  18.             data.Content = ko.mapping.fromJS(viewModel);
  19.             data.Content.ErrorMessage("@SiteResources.PageLoadError" + module);
  20.         },
  21.       });
  22.       mvcct.ko.dynamicTemplates.defaultPageStore.enablePushState(2);
  23.       mvcct.ko.dynamicTemplates.cache(5);
  24.       mvcct.ko.dynamicTemplates.service(
  25.           "@Url.Content("~/templates")" + '/',
  26.           "@Url.Content("~/templates_amd")" + '/');
  27.   </script>
  28. <script src="~/Scripts/Modules/contextRules.js"></script>
  29. <script src="~/Scripts/require.js"></script>
  30. <script src="@Url.Content("~/templates_amd/Basic.js")" type="text/javascript"></script>
  31. }


Then the host page body must get a client viewmodel aware Html helper:

  1. @{var h = Html.SendToClient(m => m, "applicationModel", "page-container");}


and must use it to render the root view placeholder:

  1. <div class="page-container">
  2.     @h.ClientTreeIteratorFor(m => m.CurrentPage, null,
  3.       "function(x){ $(mvcct.core.filterHtml(x)).fadeOut(0).fadeIn(500);}",
  4.       "function(x, y, i, f){$.when($(mvcct.core.filterHtml(x)).fadeOut(500)).always(f);}")
  5. </div>


Finally the page host should contain a javascript script tag with the code that bootstraps the SPA by creating its first virtual page, and if the application uses authorization, the code that bootstraps the SPA authorization system:

  1. <script type="text/javascript">
  2.     $(document).ready(function () {
  3.         mvcct.ko.dynamicTemplates.enableAuthorizationManager(
  4.             "@Url.Action("CurrentUser", "Account")",
  5.             "@Url.Action("Logout", "Account")",
  6.             null,
  7.             applicationModel.CurrentPage
  8.             );
  9.         applicationModel.CurrentPage(mvcct.ko.dynamicTemplates.defaultPageStore.get(
  10.             new mvcct.ko.dynamicTemplates.virtualReference("Home", "Menu")));
  11.     });
  12. </script>


That’s all for now! In the next post we will see the SPA engine authorization framework, and how the SPA framework handles context-dependent information such as the user logged in and the selected culture. A video showing the Data Moving Plug-in SPA View Engine is available here.