Angular allows to display views when they are pre-rendered in page or lazy load them on navigation. I personally don’t like pre-rendering all views in single page, because it can get really big quite fast. Rendering Razor views on server isn’t that easy out of the box, luckily there is Nuget package Westwind.Web.Mvc.

Steps to configure Razor view rendering on server:

1. Install Westwind.Web.Mvc.

2. Set up Angular routing, I am using ui-router.

$stateProvider
    .state('app', {
        url: '/app',
        abstract: true,
        templateUrl: 'views/home/base'
    }).state('app.index', {
        url: '/index',
        templateUrl: 'views/home/index'
    })

3. Create route for loading views.

routes.MapRoute(
    name: "Views",
    url: "views/{ctrl}/{view}",
    defaults: new { controller = "Views", action = "get" });

4. Create view rendering controller, which is basically one-liner:

public class ViewsController : Controller
{

    public ActionResult Get(string ctrl, string view)
    {
        var path = $"~/views/{ctrl}/{view}.cshtml";

        return Content(ViewRenderer.RenderPartialView(path), "text/html", Encoding.UTF8);
    }

}

And that’s it. There is one downside of this quick demo, if partial view has other partial views inside, they will not be rendered and exception will be thrown. Exception will say that it didn’t find that inner partial view, because we haven’t specified request context and controller and Razor view engine don’t know where to look for it.

 

Simple project that I put together for demo.

Comments


Comments are closed