Page 34 - MSDN Magazine, March 2018
P. 34
ASP.NET
Use Razor to Generate
HTML for Templates in a
Single-Page App
Nick Harrison
Single-Page Application (SPA) apps are very popular and for good reason. Users expect Web apps to be fast, engaging and work on every device from smartphones to the widest-screen desktops. Beyond that, they need to be secure, visually engaging and do something useful. That’s a lot to ask for from a Web app, but really this is only the starting point.
As users started expecting more from Web applications, there was an explosion of client-side frameworks to “help” by providing
a client-side implementation of the Model-View-ViewModel (MVVM) pattern. It can seem like there’s a new framework every week. Some have proven to be helpful, others not so much. But they all implement the design pattern differently, adding new features or solving recurring problems in their own ways. Each framework takes a different approach toward the design pattern, with a unique syntax for templates and introducing custom con- cepts like factories, modules and observables. The result is a sharp learning curve that can frustrate developers trying to stay current as new frameworks go in and out of vogue. Anything we can do to ease the learning curve is a good thing.
Having client-side frameworks implement the MVVM pat- tern and ASP.NET implement the MVC pattern on the server has led to some confusion. How do you blend server-side MVC with client-side MVVM? For many, the answer is simple: They don’t blend. The common approach is to build static HTML pages or fragments and serve them up to the client with minimal server-side processing. In this scenario, Web API controllers may often replace the processing that would have been handled by the MVC Controller in the past.
As Figure 1 shows, there are minimal requirements for the Web Server and a full-fledged server for the Web API, and both servers need to be accessible from outside the firewall.
This arrangement provides good separation of concerns, and many applications have been written following this pattern, but as a developer, you’re leaving a lot on the table. ASP.NET has a lot more
This article discusses:
• Using scaffolding to automate generating views based on models shared between the Web application and the API
• Using T4 to customize the views generated to support working with AngularJS and KnockOut
• UsingEditorTemplatestoprovideglobaleditorsintheWebapplica- tion based on the data type of the property in the underlying model
• Using jQuery Validations to enable client-side validations mirroring validations automatically performed on the server
Technologies discussed:
Visual Studio 2017, T4 Templates, Scaffolding Templates, Editor Templates
Code download available at:
bit.ly/2nps4yz
28 msdn magazine