Angular Routing with Asp.net mvc areas and cshtml not working - angularjs

My layout.cshtml contains:
<li>User</li>
<div ng-view></div>
This is my controller:
and its action methods:
public class UserController : Controller
{
// GET: Admin/Default
BMS2Entities _db = new BMS2Entities();
public ActionResult Index()
{
var emp = _db.AspNetUsers.ToList();
return Json(emp, JsonRequestBehavior.AllowGet);
}
And index.cshtml and index.js file inside:
index.js contains server call to usercontroller inside admin area:
app.controller('userController', function ($scope, $http) {
$http({ method: 'Get', url: 'Areas/Admin/User/Index' })
.then(function (response) {
$scope.depts = response.data;
});
});
and finally myapp.js file for routing:
var app = angular.module('myAppS', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.when('/User', {
templateUrl: 'Areas/Admin/Views/User/Index.cshtml',
controller: 'userController'
});
$routeProvider.otherwise({
redirectTo: '/'
});
});
but the codes are not working and it does not display cshtml and shows
https://localhost:44382/Common/Home#/User in the browser.

$routeProvider.when('/User', {
templateUrl: 'Areas/Admin/Views/User/Index.cshtml',
controller: 'userController'
});
You need to prefix root path in templateUrl and same thing in while calling controller's action.

Did you write ng-app directive in layout.cshtml?
And I think the syntax for tag should be like
User
Hope this Helps!

Related

Angular Routing and Binding data from controller

I have my angular routing like th below code
var app = angular.module('mainApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: '/DeclarationForms/V1/EmployeeProfile.html',
controller: 'empController'
}).when('/DeclarationAndIndemnityBond.html', {
templateUrl: '/DeclarationForms/V1/DeclarationAndIndemnityBond.html',
controller: 'declarationController'
}).otherwise({
redirectTo: "/"
});
app.controller('empController', function ($scope, $http) {
var resultPromise = $http.get("../ViewForms/GetData/", { params: { ProcName: "SP_EmployeeProfile_GetList" } });
resultPromise.success(function (data) {
console.log(data);
$scope.employeeProfile = data;
});
});
});
The empController calls my controller action with a parameter as per the code
$http.get("../ViewForms/GetData/", { params: { ProcName: "SP_EmployeeProfile_GetList" } });
The controller's action code is as follows
[HttpGet]
[AllowAnonymous]
public ActionResult GetData(string ProcName)
{
if(Session["UserJDRECID"]==null || Session["UserJDRECID"].ToString()=="0")
{
return RedirectToAction("Login", "User_Login");
}
else
{
var UsrJDID = Convert.ToInt32(Session["UserJDRECID"]);
DataSet dt = Helper.PopulateData(ProcName, UsrJDID);
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(dt);
return Json(JSONString, JsonRequestBehavior.AllowGet);
}
}
The form get loaded properly as per the code
templateUrl: '/DeclarationForms/V1/EmployeeProfile.html',
but it don't call my action GetData from where I suppose to bind the EmployeeProfile.html
If I change my angular controller like below code this still don't work
app.controller('empController', function ($scope)
{
console.log("hi"); alert();
});
My console gives below error
Error: error:areq
Bad Argument
Please help me I stuck here.
Thanks in advance.
You can't use "../" inside your $http.get.
I don`t know how your project is setup, but you can try:
$http.get("/ViewForms/GetData/", { params: { ProcName: "SP_EmployeeProfile_GetList" } });
In that case the ViewForms is the name of your controller and it needs to be in the root or pass the complete url. Make sure you are passing all the folders then Controller then your action.
Example: http://www.dotnetcurry.com/angularjs/1202/angular-http-service-aspnet-mvc
I change my code as follows and this worked for me.
var app = angular.module('mainApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.
when('/', {
templateUrl: '/DeclarationForms/V1/EmployeeProfile.html',
controller: 'empController'
})
otherwise({
redirectTo: "/"
});
});
app.controller('empController', ['$scope', '$http', EmployeeProfile]);
function EmployeeProfile($scope, $http) {
$http.get("../ViewForms/GetData", { params: { ProcName: "SP_EmployeeProfile_GetList" } })//Done
.then(function (response) {
var mydata = $.parseJSON((response.data));
$scope.employeeProfile = $.parseJSON(mydata);
});
}

HTTP ERROR 404 after page refresh in ANgular JS1

I am using http-server package to run my angular js project. My directory structure is below:-
angulardemo/app/public/controller
angulardemo/app/public/app.js
angulardemo/app/public/index.html
angulardemo/app/public/view
ang my app.js file is
var app = angular.module('angulardemo', ['ngRoute', 'ngCookies'])
.constant('API_URL', 'http://127.0.0.1:8001')
.config(function ($routeProvider, $locationProvider, $httpProvider) {
$httpProvider.defaults.headers.common = {'Content-Type' : 'application/json'};
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.put = {};
$httpProvider.defaults.headers.patch = {};
/**
*
* Checks for url access
*/
resolver = function (access){
return {
load: function($q, AuthService, $location){
if(access){
return true
}else{
if(AuthService.checkLogin()){
return true;
}
else{
$location.path("/login");
}
}
}
}
}
$routeProvider
.when('/', {
templateUrl : "/view/home.html",
controller : 'PagesController'
})
.when('/home', {
templateUrl : "/view/home.html",
controller : 'PagesController'
})
.when('/about', {
templateUrl : "/view/about.html",
controller : 'PagesController'
})
.when('/team', {
templateUrl : "/view/team.html",
controller : 'PagesController'
})
.when('/work', {
templateUrl : "/view/work.html",
controller : 'PagesController'
})
.when('/price', {
templateUrl : "/view/price.html",
controller : 'PagesController'
})
.when('/users/:user_type', {
templateUrl : "/view/developers.html",
controller : 'UsersController'
})
.when('/user/show/:id', {
templateUrl : "/view/user.details.html",
controller : 'UsersController'
})
.when('/contact', {
templateUrl : "/view/contact.html",
controller : 'PagesController'
})
.when('/register', {
controller: 'AuthController',
templateUrl: '/view/auth/register.html',
resolve:{
loggedIn: function(AuthService, $location){
if(!AuthService.checkLogin())
return true;
else
$location.path("/home");
}
}
})
.when('/login', {
controller: 'AuthController',
templateUrl: '/view/auth/login.html',
resolve:{
loggedIn: function(AuthService, $location){
if(!AuthService.checkLogin())
return true;
else
$location.path("/home");
}
}
})
.when('/dashboard', {
controller: 'DashboardController',
templateUrl: '/view/dashboard/index.html',
pageTitle: 'dashboard',
resolve:resolver(false)
})
.when('/users_personal/:id', {
controller: 'UsersController',
templateUrl: '/view/users/personal.html',
pageTitle: 'personal_details',
resolve:resolver(false)
})
.when('/users_edu/:id', {
controller: 'UsersController',
templateUrl: '/view/users/edu.html',
pageTitle: 'edu_details',
resolve:resolver(false)
})
.when('/users_contact/:id', {
controller: 'UsersController',
templateUrl: '/view/users/contact.html',
pageTitle: 'contact_details',
resolve:resolver(false)
})
.when('/users_other/:id', {
controller: 'UsersController',
templateUrl: '/view/users/other.html',
pageTitle: 'other',
resolve:resolver(false)
})
.when('/logout', {
resolve : {
logout: function ($routeParams, $location, $http, API_URL){
$http.get(API_URL + "/api/auth/logout").success(function (response) {
if(response === "OK"){
localStorage.removeItem('auth');
$location.path('/login').replace();
}
})
}
}
})
.otherwise({
redirectTo: '/',
});
$locationProvider.html5Mode({
enabled: true,
requireBase: false
}).hashPrefix('*');
}).run(['$http', '$cookies', function($http, $cookies) {
$http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
}]);
when I am running project using "http-server" with in the app directory command I got url as http://127.0.0.1:8080
http://192.168.10.137:8080
all the pages are working fine but when I am refreshing the page I am getting This 127.0.0.1 page can’t be found
No web page was found for the web address: http://127.0.0.1:8080/team
HTTP ERROR 404
So can anyone please tell that what wrong thing is here. and provide the solution.
See the directory structure in git hub:-
https://github.com/sanjaysamant/angulardemo/tree/local/app
Angular js files are in the public directory
Thanks
Please see terminal screen shot:
Whenever you are on a sub-URL such as /team and you refresh the page, the Node-Server looks for a HTML-File that is in the folder team on your server, which is not what you want. You need the server to redirect all those URL's to your index.html so that it loads the Angular Application, which can then properly initialize the correct page.
You can try the following in your server.js file:
//routes
app.use('/api/auth', require('./controllers/auth/auth.controller'));
app.use('/api/users', require('./controllers/users/users.controller'));
app.use('/api/user/', require('./controllers/users/users.controller'));
// Redirect unmatched routes (All specific routes such as /api/* need to be before this call)
app.use(redirectUnmatched);
function redirectUnmatched(req, res) {
res.redirect("/");
}
What #Chnoch suggested is correct, however I want to give you a different approach.
app.get('*', function(req, res)
{
res.send('/path/to/index.html');
});
Because all requests for a page will be a GET requests, you don't need to specify POST, and with this approach it will preserve the current URL you are on (eg. if you were on http://127.0.0.1:8080/team you will refresh and still be on /team), wheras #Chnoch's approach will always redirect you back to http://127.0.0.1:8080/.
What this will do is for any request that can't be resolved by the Node server, it will just render plain index page that can then be handled by Angular's ngRoute to display templates (you can also use templating engines like EJS or Pug with this, just replace the res.send with the rendering function).
Just make sure that the above code is after ALL other routes you want to be resolved by the Node server (eg. your API etc.) so it doesn't interfere with routes after it, since this is a catch all route.

Manually changing the URL does not call the controller in AngularJS

I have a application with main pages as app.html and my controller is app.js. The following is the code in app.js:
angular.module(constants.MODULE_NAME).controller('AppCtrl', function ($scope, $state, $log, $http) {
$scope.role = '';
$http.get("htttp://localhost:8082/service/getUserRole")
.then(function (response) {
$scope.role = response.data.context;
debugger;
if ($scope.role.toLowerCase() == "hr") {
//direct view to hr dashboard
$state.go("app.hr");
} else if($scope.context.toLowerCase() == "eemployee"){
//direct view to employee dashboard
$state.go("app.employee");
}
else{
//do nothing
$state.go("app");
}});
});
So when I run this website the controller is called and based on the value of role the respective dashboard is displayed.When the website runs it hits http://localhost:9080/#/ which is calling the above controller and redirects too http://localhost:9080/#/hr/dashboard (or) http://localhost:9080/#/employee/dashboard.
I have the following in my router.js
export default ['$stateProvider', '$urlRouterProvider', ($stateProvider, $urlRouterProvider) => {
$stateProvider
.state('app', {
url: '/',
template: require('./app.html'),
controller: 'AppCtrl',
controllerAs: 'app'
})
.state('app.hr', {
url: 'hr/dashboard',
template: require('./hr/dashboard/index.html'),
controller: 'HRCtrl',
controllerAs: 'hrctrl'
})
.state('app.employee', {
url: 'employee/dashboard',
template: require('./employee/dashboard/index.html'),
controller: 'EMPCtrl',
controllerAs: 'empctrl'
});
$urlRouterProvider.otherwise('/');
}];
Now when I change the URL to http://localhost:9080/#/ and hit enter then the controller is not getting called. But when I do a refresh the controller gets called. Can I know how I can fix this issue.

Keeping controllers in different files not working in Angular

I am currently defining my global module in my routes.js, but for some reason the other controllers are not being created and I keep getting errors that say that my main app module 'LiveAPP' is not available. Here is my code:
routes.js
angular.module('LiveAPP', ['ngRoute'])
.config(function($routeProvider, $httpProvider) {
$routeProvider
.when('/', {
templateUrl : '/home.html',
controller : 'mainCtrl'
})
.when('/signup',{
templateUrl : '/signup.html',
controller : 'signUpCtrl'
})
.when('/artist',{
templateUrl : '/artistpage.html',
controller : 'artistCtrl'
})
})
mainCtrl.js
angular.module('LiveAPP')
.controller('mainCtrl', ['$scope','$http', '$location',mainCtrl]);
function mainCtrl($scope,$http,$location){
$scope.somefunc = function(artistname){
dataFactory.ArtistfromSpotify()
.success(function(data, status, headers, config){
console.log(data)
})
}
};
signUpCtrl
angular.module('LiveAPP')
.controller('signUpCtrl', ['$scope','$http',signUpCtrl]);
function signUpCtrl($scope,$http){
$scope.user = {
email:'',
password:''
}
$scope.postreq = function(user){
$http({
method: "post",
url: "/signup",
data:{
user_username:user.email,
user_password:user.password
}
}).success(function(data){
console.log("User posted to the database")
});
};
}
artistCtrl
angular.module('LiveAPP')
.controller('artistCtrl', ['$scope',function($scope){
$scope.myRating =
{number:3}
}])
.directive("rateYo", function() {
return {
restrict: "A",
scope: {
rating: "="
},
template: "<div id='rateYo'></div>",
link: function( scope, ele, attrs ) {
console.log(scope.rating.number)
$(ele).rateYo({
rating: scope.rating.number
});
}
};
});
I was under the impression that I could retrieve the main liveAPP module and add controllers in other files by using angular.model('liveAPP').controller(...) For some reason it's not working. Anyone have any idea?
To elaborate on my comment above, when you re-use the same module across files, you need to load the files in the right order to satisfy dependencies as well as ensure the module is created before being used.
An easy way to avoid this problem is to specify one module per file. For example
mainCtrl.js
(function() {
angular.module('LiveAPP.main', [])
.controller('mainCtrl', ...);
})();
and in your routes.js
(function() {
angular.module('LiveAPP', [
'ngRoute',
'LiveAPP.main'
])
.config(function($routeProvider, $httpProvider) {
$routeProvider.when('/', {
templateUrl: '/home.html',
controller: 'mainCtrl'
})...
});
})();
It's likely that your html file is including the js files in the wrong order. You need to make sure that routes.js appears first in the html.
You need to change signUpCtrl.js to
angular.module('LiveAPP.controller', [])
.controller('signUpCtrl', ['$scope','$http',signUpCtrl]);
and inject LiveAPP.controller to your global module
angular.module('LiveAPP', ['ngRoute', 'LiveAPP.controller'])
You cannot have LiveAPP in more than one module. Make the same updates on all of your controllers and inject that module names in routes.js

Working with AngularJS $locationProvider in MVC5

I am trying to change the URL of the page if an $html callback is a success.
Module:
var app = angular.module('mymodule', ['ngRoute','ui.bootstrap']);
app.config(function($locationProvider, $routeProvider) {
$locationProvider.html5Mode(true);
$routeProvider.
when('/Home/Index', {
templateUrl: '/Home/Index',
controller: 'HomeController'
});
});
Controller:
$http({
method: 'POST',
url: '/User/InsertInitialUserInfo',
data: insertUserParams
}).success(function (data, status) {
$location.url("/Home/Index");
}).error(function (data, status) {
console.log(status);
});
MVC Controller
public ActionResult Index()
{
return View();
}
After my controller code runs the URL changes from : localhost:xxxx/Home/Register to localhost:xxxx/Home/Index
But the view doesn't change. What am I missing?
You are only missing one important component, the ng-view declaration in your view
<div ng-view></div>
This is placeholder for the templates you specify in the app.config.

Resources