By default when you use the Durandal MVC template, your views should be created as plain html files.
But what if you want to use ASP.NET MVC Razor files(.cshtml) instead? This is perfectly possible but requires some configuration work from you:
First, let’s switch the Durandal view extension from .html(the default) to .cshtml. Open up the main.js file and set the viewExtension property on the viewEngine object:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
requirejs.config({ | |
paths: { | |
'text': '../Scripts/text', | |
'durandal': '../Scripts/durandal', | |
'plugins': '../Scripts/durandal/plugins', | |
'transitions': '../Scripts/durandal/transitions' | |
} | |
}); | |
define('jquery', function() { return jQuery; }); | |
define('knockout', ko); | |
define(['durandal/system', 'durandal/app', 'durandal/viewLocator', 'durandal/viewEngine'], function (system, app, viewLocator,viewEngine) { | |
//>>excludeStart("build", true); | |
system.debug(true); | |
//>>excludeEnd("build"); | |
app.title = 'Durandal Starter Kit'; | |
app.configurePlugins({ | |
router: true, | |
dialog: true, | |
widget: true | |
}); | |
app.start().then(function() { | |
//Replace 'viewmodels' in the moduleId with 'views' to locate the view. | |
//Look for partial views in a 'views' folder in the root. | |
viewLocator.useConvention(); | |
//by default durandal expects html files, override this | |
//Use the MVC route | |
viewEngine.viewExtension = ".cshtml"; | |
//Show the app by setting the root view model for our application with a transition. | |
app.setRoot('features/shell', 'entrance'); | |
}); | |
}); |
The next step is to create a generic controller that will serve .cshtml files:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DurandalViewController : Controller | |
{ | |
// | |
// GET: /App/views/{viewName}.cshtml | |
[HttpGet] | |
public ActionResult Get(string viewName) | |
{ | |
return View("~/App/views/" + viewName + ".cshtml"); | |
} | |
} |
And of course, don’t forget to add a route that matches this controller:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
routes.MapRoute( | |
name: "Durandal App Views", | |
url: "App/views/{viewName}.cshtml", | |
defaults: new { controller = "DurandalView", action = "Get" } | |
); |
As a last step copy the web.config file from Views/web.config to /App/views/web.config (so Razor views work in this location):