javascript 如何使用 AngularJS 和 asp.net MVC 4 从视图文件夹加载模板

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17256349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:40:01  来源:igfitidea点击:

How to load templates from views folder with AngularJS and asp.net MVC 4

javascriptasp.net-mvc-4angularjs

提问by SolidSnake

Apparently, I'm very new to angularJS and asp.net MVC4. here's the scenario:

显然,我对 angularJS 和 asp.net MVC4 很陌生。这是场景:

I have a simple MVC4 project which contains 1 controller and 1 view (i.e: home.cshtml). Now I have added HTML file (i.e: search.html) to a folder called "Templates" which is located in the main directory of the project (outside of views folder). What I want is to load "search.html" with angularJS so I can include it to the "home.cshtml" how can I do that? here is what I've got so far:

我有一个简单的 MVC4 项目,其中包含 1 个控制器和 1 个视图(即:home.cshtml)。现在我已将 HTML 文件(即:search.html)添加到名为“Templates”的文件夹中,该文件夹位于项目的主目录中(在 views 文件夹之外)。我想要的是用 angularJS 加载“search.html”,这样我就可以将它包含到“home.cshtml”中,我该怎么做?这是我到目前为止所得到的:

angular Module:(Located in Scripts Folder)

角度模块:(位于脚本文件夹中)

var bfapp = angular.module("blogfinder", []).config(function ($routeProvider) {
    $routeProvider.when('/search', {
        templateURL: '/Templates/search.html',
        controller: 'SearchController'
    });

    $routeProvider.otherwise({ redirectTo: '/search' });

});

bfapp.controller('SearchController', function () {

});

hope this clear for you. any help would be appreciated! Thanks..

希望这对你来说很清楚。任何帮助,将不胜感激!谢谢..

回答by apexdodge

It took me a while to figure out how to get angularjs working with asp.net mvc -- this isn't 100% the way you did things, but you might want to reconsider to this approach (it's not that much different anyway)

我花了一段时间才弄清楚如何让 angularjs 与 asp.net mvc 一起工作——这不是你做事的 100% 方式,但你可能想重新考虑这种方法(无论如何它并没有太大不同)

var AccountApp = angular.module("AccountApp", ['$strap.directives', 'ngResource', 'ngGrid', 'filePickers']).
config(function ($routeProvider) {
    $routeProvider.
        when('/', { controller: ListCtrl, templateUrl: 'Templates/Account/List' }).
        when('/', { controller: EditCtrl, templateUrl: 'Templates/Account/Edit' }).
        otherwise({ redirectTo: '/' });
});

Ok, notice I am calling Templates/Account/List.

好的,注意我正在调用 Templates/Account/List。

In my RouteConfig.cs

在我的 RouteConfig.cs

        routes.MapRoute(
            name: "Templates",
            url: "Templates/{controller}/{template}",
            defaults: new { action = "Template" }
        );

Now in each controller, I have this corresponding action that directs the call to the appropriate partial view:

现在,在每个控制器中,我都有相应的操作将调用定向到适当的局部视图:

    public ActionResult Template(string template)
    {
        switch (template.ToLower())
        {
            case "list":
                return PartialView("~/Views/Account/Partials/List.cshtml");
            case "create":
                return PartialView("~/Views/Account/Partials/Create.cshtml");
            case "edit":
                return PartialView("~/Views/Account/Partials/Edit.cshtml");
            case "detail":
                return PartialView("~/Views/Account/Partials/Detail.cshtml");
            default:
                throw new Exception("template not known");
        }
    }

It all starts off with the Index() action in the controller though.

不过,这一切都始于控制器中的 Index() 操作。

    public ActionResult Index()
    {
        return View();
    }

Putting it all together, my directory structure looks like this.

把它们放在一起,我的目录结构看起来像这样。

/Views
    /Account
        /Partials
             List.cshtml
             Create.cshtml
             Edit.cshtml
             Detail.cshtml
        Index.cshtml

I'm biased, since this is my approach, but I think it makes things super simple and organized nicely. Index.cshtml contains the ng-view and all of the other parts of the application are nicely contained in partial views that are loaded through that Template action. Hope this helps.

我有偏见,因为这是我的方法,但我认为它使事情变得非常简单并且组织得很好。Index.cshtml 包含 ng-view,应用程序的所有其他部分都很好地包含在通过该模板操作加载的部分视图中。希望这可以帮助。

回答by u5032788

I'm facing the same problem,and I got the solution.

我面临同样的问题,我得到了解决方案。

Sounds like you wanna let the 'Home.cshtml' to be the base and load in the 'search.html' by the AngularJS's routing,right? (Just like the MVC-way a little be:The '_Layout.cshtml' is the base,let us can load in different views we navigate.)

听起来你想让'Home.cshtml'成为基础并通过AngularJS的路由加载到'search.html'中,对吗?(有点像 MVC 的方式:'_Layout.cshtml' 是基础,让我们可以在我们导航的不同视图中加载。)

To reach that,just add the ng-view tag into the Home.cshtml!The AngularJS routing will work for you.

为此,只需将 ng-view 标签添加到 Home.cshtml 中!AngularJS 路由将为您工作。

MAKE SURE the views loaded do not put in the Views folder!(Or you must access the views by firing requests to the controllers to obtain them.)

确保加载的视图没有放在 Views 文件夹中!(或者您必须通过向控制器发出请求来访问视图以获取它们。)



Here is the example.

这是示例。

We have a Server Side (ASP.NET MVC) Controller :

我们有一个服务器端(ASP.NET MVC)控制器:

HomeController with three actions.

具有三个动作的 HomeController。

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult GetPartial1()
    {
        return View();
    }

    public ActionResult GetPartial2()
    {
        return View();
    }
}

And in your angular code(app.js) just set the URL of the ng-view to these action to obtain the views.

并且在您的角度代码(app.js)中,只需将 ng-view 的 URL 设置为这些操作即可获取视图。

angular.module('myApp', [
    'myApp.controllers',
    'ngRoute'
]);

angular.module('myApp').config(function ($routeProvider, $locationProvider) {
    $routeProvider.when('/view1', {
        controller: 'HomeController',
        templateUrl:'Home/GetPartial1'
    }).when('/view2', {
        controller: 'HomeController',
        templateUrl:'Home/GetPartial2'
    }).otherwise({redirectTo:'/view1'});
    $locationProvider.html5Mode({
        enabled: true,
        requireBase: false
    });
});