javascript - 如何将 .cshtml 和 .html 文件与 Durandal 一起使用

标签 javascript asp.net-mvc durandal

我开始将 DurandalJs 框架与 asp.net MVC 结合使用。它运行完美。

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

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

但是 DurandalJs 仍然尝试获取 .html 文件作为 View 。

所以我更正了 viewEngine.js 文件:

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

但现在 DurandalJs 要求所有 View 文件都应具有“.cshtml”扩展名。

那么我可以同时使用“.html”和“.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;
    }
}

现在 durandal 应用程序可以使用 .html 和 .cshtml。

关于javascript - 如何将 .cshtml 和 .html 文件与 Durandal 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15570942/

相关文章:

javascript - MVC5 Controller 操作未从 JSON AJAX Post 调用

javascript - 使用 SignalR 作为 EventBus 事件的广播者

javascript - 为什么 Durandal 入门教程中 text.js 的请求路径错误?

java - GWT SimplePager - 为每个下一个和上一个添加历史记录

javascript - 在 sails js Node 框架中创建 url

c# - ASP.NET 成员更改密码不起作用

c# - 为什么 MVC 在 GET 上使用模型状态而不是提供的模型

javascript - Durandal 激活剂

javascript - 阅读另一个域上 iframe 的源代码

javascript - 我希望在未填写必填字段时不打开模式框