Why this is not loading view1.cshtml in MVC empty

2019-06-14 17:04发布

问题:

I am learning Angular. I am watching a 2 years old video, and I am trying to use route concept and using in view1.CShtml (Remember, its CShtml and not html, while in the video, he uses html).

I also find it wierd that Views path starts as ~Views/View1.cshtml (Fair enough I have it in Views folder) on contrary to Partial/View1 where the video demonstrator has. Now, I do not understand what is this "~" for when I have similar directory structure like demonstrator.

Also, sadly, the view1 is not loading :( What is the problem? Of course he use single module and controller, but I am trying to use dependent module also for my own learning....What's the problem here?

    angular.module('App', ['myFirstApp']).controller('Fir', function ($scope) {
        $scope.Customers = [
      { name: 'Kiam', city: 'Los Angeles' },
      { name: 'Se', city: 'Los Vegas' }
        ]
    }).config(function ($routeProvider) {
        $routeProvider
        .when('/View1',
        {
            controller: 'Fir',
            templateUrl: '~Views/View1.cshtml'
        })
        .when('/View2',
        {
            controller: 'First',
            templateUrl: '~Views/View2.cshtml'
        })
        .otherwise({ redirectTo: '/View1' });
    });


    var temp = angular.module('myFirstApp', []);

    var controllerCollection = {};
    controllerCollection.First = function ($scope) {
        $scope.Customers = [
      { name: 'Sita', city: 'Los Angeles' },
      { name: 'Ram', city: 'Los Vegas' },

        ]
    };

    temp.controller(controllerCollection);

回答1:

.cshtml pages are C# razor pages, which need to be loaded using ASP.net view engine, Like you could declare one action inside A controller and do return a cshtml view from there

Code

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

Or else you need to create a static folder, which will not been included in Views folder, Asp.net restricted access to the views folder.

See reference SO Answer



回答2:

you could try like this .when('/View1', { controller: 'Fir', templateUrl: '/MyViews/View1'}), it's enough. and also check the route config the routing path is added or not. If you are using the $routeprovider it will automatically generated the routing path in global.asax.

No need to specify additionally the .cshtml for the view page to be displayed.