2013-03-22 29 views
0

我开始使用带有asp.net MVC的DurandalJs框架。它运作完美。如何在Durandal中使用.cshtml和.html文件

但现在我需要使用.cshtml文件作为durandal的视图。所以我添加到根目录web.config

<add key="webpages:Enabled" value="true" /> 

但DurandalJs仍然尝试获取.html文件作为视图。

所以我纠正viewEngine.js文件:

return { 
    viewExtension: '.cshtml', 
    viewPlugin: 'text', 

但现在DurandalJs要求所有意见的文件应该有 “.cshtml” 扩展名。

那么我可以一起使用“.html”和“.cshtml”文件吗?

回答

2

在main.js我添加的行:

viewLocator.useConvention('viewmodels', 'ViewsProxy/GetView?name=', 'ViewsProxy/GetView?name='); 

并实现了ViewsProxyController象下面这样:

public class ViewsProxyController : Controller 
{ 
    public ActionResult GetView(string name) 
    { 
     string viewRelativePath = GetRelativePath(name); 
     string viewAbsolutePath = HttpContext.Server.MapPath(viewRelativePath); 

     if (!System.IO.File.Exists(viewAbsolutePath)) 
     { 
      viewAbsolutePath = ReplaceHtmlWithCshtml(viewAbsolutePath); 
      if (System.IO.File.Exists(viewAbsolutePath)) 
      { 
       System.Web.HttpContext.Current.Cache.SetIsHtmlView(name, false); 
       viewRelativePath = ReplaceHtmlWithCshtml(viewRelativePath); 
       return PartialView(viewRelativePath); 
      } 
      throw new FileNotFoundException(); 
     } 

     FilePathResult filePathResult = new FilePathResult(viewAbsolutePath, "text/html"); 
     return filePathResult; 
    } 

    private string ReplaceHtmlWithCshtml(string path) 
    { 
     string result = Regex.Replace(path, @"\.html$", ".cshtml"); 
     return result; 
    } 

    private string GetRelativePath(string name) 
    { 
     string result = string.Format("{0}{1}", AppConfigManager.DurandalViewsFolder, name); 
     return result; 
    } 
} 

所以现在迪朗达尔应用程序可以与.html和.cshtml工作。

1

您需要更改路由以接受cshtml作为MVC路由的扩展。

routes.MapRoute(
    name: "Default", 
    url: "{controller}/{action}.cshtml", 
    defaults: new { controller = "Home", action = "Index", namespaces: new string[] { "PAWS.Web.Controllers" } 
); 

此外,您需要确保您的应用程序池运行在集成和非经典之下。

但我不建议这样做。你应该试着不要让服务器渲染你的任何HTML。原因解释here

相关问题