Search code examples
c#asp.net-mvc-4durandalhottowel

SPA (Hot Towel) - how to change convention to process/request Razor views?


Using the Hot Towel SPA template as an example, say I have a requirement for an admin link and view which only appears for logged in users with an Administrator role. Should be simple enough, right?

With a Razor (or WebForms or whatever, doesn't matter really) view, it would be a simple matter of having this in nav.cshtml:

if(HasRole("Administrator")){
    @* hyperlink here eg /Views/Admin *@
}

and have an action on ViewsController like:

return PartialView("Administrator");

It must surely be possible to change convention so that, for example, the route for Widget looks up http://server/Views/widget instead of http://server/App/views/widget.htm and (perhaps selectively?) disable caching of view requests.

The main alternative as I see it would be exposing things which shouldn't be exposed to anyone who views the page's source from the browser. If something shouldn't be displayed, I'd rather not include it in the HTML output at all rather than send it all down and selectively hide/display client-side.


Solution

  • So here's what I've got:

    In main.js, replace the viewLocator.useConvention call with:

    viewLocator.useConvention(null,"/Views",null);
    

    Create a ViewsController with:

    public class ViewsController : Controller
    {
        public ActionResult Render(string id)
        {
            return PartialView(id);
        }
    }
    

    and add the following to App_Start\RouteConfig.cs:

    routes.MapRoute(
                name: "SPAViews",
                url: "Views/{id}",
                defaults: new { action = "Render" }
    );
    

    It doesn't take into account the client caching requests but it's 90% of the way there.