我如何使用.cshtml和.html文件与Durandal

How can I use .cshtml and .html files with Durandal

本文关键字:文件 Durandal html 何使用 cshtml      更新时间:2023-09-26

我开始使用DurandalJs框架与asp.net MVC。它工作得很好。

但是现在我需要使用。cshtml文件作为持久性的视图。所以我在根目录中添加了web.config

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

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

所以我更正viewEngine.js文件:

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

但是现在DurandalJs要求所有的视图文件都应该有"。cshtml"扩展。

所以我可以使用".html"answers"。Cshtml文件在一起?

在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。

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

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

您还需要确保您的应用程序池在集成而不是经典的情况下运行。

但我不建议这样做。您应该尝试不让服务器呈现任何HTML。原因如下

看看Durandal viewEngineviewLocator定制,它们允许使用本地'.html'和远程'。

是否可以有多个viewEngine.viewExtension