An ASP.NET View Engine that specializes in sharing partial views between client and server.

Right now, this project is in an exploratory phase. The goal is to have a full blown nuget package that can be imported into your project.

The server renders the initial view of your data to HTML and sends that to the client. The client can then re-render the same exact template with new or modified data without round-tripping to the server.

To get started, add the following to your ASP.NET MVC 4 Web Application project (will be delivered with nuget soon):
  • Add reference to the assemblies "JsViewEngine.dll" and "Jurassic.dll"
  • Copy "JsRender.js" into you Scripts folder
  • Copy "viewconverters.js" into your Scripts folder

In your Global.asax.cs file, add the following to your Application_Start() method:

            //Register your View Engine here
            ViewEngines.Engines.Add(
                new JsTemplateViewEngine()
                    {
                        ScriptPathJsrenderJs = "~/Scripts/jsrender.js",
                        ScriptPathViewConvertersJs = "~/Scripts/viewconverters.js"
                    });	


To create your first server rendered partial, we are going to create a ".jsrender" file to hold the template:

movieTemplate.jsrender
<div>
	{{:#index+1}}: <b>{{>name}}</b> ({{>releaseYear}})
</div>	


Then, in your Razor .cshtml page where you want to render your data with a partial, call Html.Partial() as you would with any partial:

<div id="movieList">
	@Html.Partial("movieTemplate", Model.Movies)
</div>


You now have your data being rendered as HTML and sent to the client web browser. Next we need to send the client the template and the data so they can render if something changes on their end.

Note the <div id="movieList">. This will be used for dynamic updating.

Add the following line to your .cshtml Razor page:
	@JsTemplates.RenderTemplateBlock("movieTemplate")


This outputs the contents of the script in a text/x-jsrender script block like this:
<script id="movieTemplate" type="text/x-jsrender">
	<div>
		{{:#index+1}}: <b>{{>name}}</b> ({{>releaseYear}})
	</div>
</script>


This can be used by your JavaScript to re-render the HTML as needed. We will also send the client an initial copy of our data so they have something to work with:

	<!-- Import jsrender.js -->
	<script src="/Scripts/jsrender.js"></script>

    <script type="text/javascript">
        var movies = @JsTemplates.ObjectToJson(Model.Movies);

        // Render the template with the movies data and insert
        // the rendered HTML under the "movieList" element
        $( "#movieList" ).html(
            $( "#movieTemplate" ).render( movies )
        );
    </script>


And thats it! With just these peices, you can re-use a partial template without duplication.

Last edited Nov 17, 2012 at 6:54 AM by shiften, version 5