【问题标题】:How to use ASP.Net MVC View .csthml as Angular View instead of .html如何在 Angular 视图中使用 ASP.Net MVC 视图 .cshtml 而不是 .html
【发布时间】:2017-02-16 14:02:21
【问题描述】:

我正在尝试使用 Angulars $routeProvider 将模板加载到我的 Views 文件夹中的 .cshtml 文件中的容器中。

我在 Angular 中使用此代码得到 404:

.when('#/second',{ urlTemplate:"Views/second.cshtml",controller:"MainController"})

Angular 找不到 second.cshtml 文件。 为什么? 不能使用.cshtml文件吗?

【问题讨论】:

  • 有可能。我们已经编写了一些使用 .cshtml 作为 Angular 视图的 Angular 应用程序。您需要执行几个步骤。让我现在写一个指令,然后在这里发布。
  • 我发布了我的answer仅供参考:Angular 2 就在取芯器周围。您想使用 Angular 1.5 的组件,以便轻松迁移到 Angular 2。

标签: angularjs asp.net-mvc asp.net-web-api ng-view


【解决方案1】:

您不能直接提供.cshtml 文件。

如果没有服务器端逻辑,则需要将文件转换为 .html 文件,或者如果有逻辑,则需要使用标准 MVC 路由方式请求它:/MyController/MyAction

【讨论】:

  • 有可能。请看我的answer
【解决方案2】:

您需要配置几个步骤才能将 .cshtml 提供给客户端。

我创建了一个名为AngularAspNet at GitHub 的示例项目。

1) 创建 App 文件夹来托管 Angular 脚本。 你可以随意命名。

2) 将 .cshtml 文件放在 App/xxx/Components/ 文件夹中。确保将属性设置为内容。

我想将 Angular 视图和组件(JavaScript 文件)放在一起。原因是当项目变得更复杂时,它可以帮助我轻松找到视图和相应的组件。因此,我没有将 .js 放在 Views 文件夹中,而是将 .chtml 文件放在 App(Angular Script)文件夹中。

1) 创建一个 web.config,其中包含 BlockViewHandler

<?xml version="1.0"?>

<configuration>
  <configSections>
  ...        
  <system.webServer>
    <handlers>
      <remove name="BlockViewHandler"/>
      <add name="BlockViewHandler" path="*.cshtml" verb="*" 
          preCondition="integratedMode" 
          type="System.Web.HttpNotFoundHandler" />
    </handlers>
  </system.webServer>
   ...
</configuration>

4) 创建控制器和动作方法。

public class NgController : Controller
{
    public PartialViewResult RenderComponents(string feature, string name)
    {
        return PartialView($"~/App/{feature}/Components/{name}");
    }
}

5) 配置路由。

routes.MapRoute(
    name: "Components",
    url: "{feature}/components/{name}",
    defaults: new { controller = "Ng", action = "RenderComponents" });

信用

Building Strongly-typed AngularJS Apps with ASP.NET MVC 5 by Matt Honeycutt

AngularJS & ASP.NET MVC Playing nice Tutorial by Miguel Castro

【讨论】:

  • 提供 .cshtml 文件与拥有 .html 文件有何不同?
  • JavaScript 是一种动态语言,因此维护成本非常高。使用服务器端 cshtml 在一定程度上解决了这个问题;我可以创建强类型的 ASP.Net MVC 助手来呈现 Angular 绑定和表达式。我喜欢Axel Zaratean的帮手; 不幸的是,他停止为 his GitHub project 做出贡献。我以他为基础,并根据我的需要进行了很多修改。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-18
  • 2014-04-18
  • 1970-01-01
相关资源
最近更新 更多