How can I use cshtml files with Durandal?

后端 未结 8 2271
你的背包
你的背包 2020-12-01 01:50

I got the DurandalJS StarterKit template on VS2012... All works great...

But in some views I need to do something like that:

@if (Roles.IsUserInRole(         


        
8条回答
  •  温柔的废话
    2020-12-01 02:25

    I don't recommend that you use .cshtml files as views directly. You're better off placing the .cshtml files behind a controller.

    For example, take the HotTowel sample, edit /App/main.js, and replace the function definition with the following:

    define(['durandal/app', 
            'durandal/viewLocator', 
            'durandal/system',
            'durandal/plugins/router',
            'durandal/viewEngine', 
            'services/logger'],
    function (app, viewLocator, system, router, viewEngine, logger) {
    

    Note that we added a reference to the Durandal viewEngine. Then we need to replace

    viewLocator.useConvention();
    

    with

    viewLocator.useConvention('viewmodels', '../../dynamic'); 
    viewEngine.viewExtension = '/';
    

    The first argument to viewLocation.useConvention sets the /Apps/viewmodels/ directory as the location for the view models js files, but for the view location, uses the URL http://example.com/dynamic/, with an extension of '/'. So that if Durandal is looking for the view named 'shell', it will reference http://example.com/dynamic/shell/ (this is because the view directory is mapped relative to the viewmodels directory, hence /App/viewmodels/../../dynamic will give you simply /dynamic).

    By convention, this previous URL (http://example.com/dynamic/shell/) will be mapped to the controller DynamicController, and the action "Shell".

    After this, you simply add a controller - DynamicController.cs, like this:

    // will render dynamic views for Durandal
    public class DynamicController : Controller
    {
        public ActionResult Shell()
        {
            return View();
        }
    
        public ActionResult Home()
        {
            return View();
        }
    
        public ActionResult Nav()
        {
            return View();
        }
    
        public ActionResult Details()
        {
            return View();
        }
    
        public ActionResult Sessions()
        {
            return View();
        }
    
        public ActionResult Footer()
        {
            return View();
        }
    }
    

    Create .cshtml files for each of the above actions. This way you get to use controllers, server side IoC et al to generate dynamic views for your SPA.

提交回复
热议问题