MVC authorization not working when mixed with Angularjs - javascript

I have developed an MVC + Angularjs application, a mixed application, and Angular application's first page is my HomeController's Index view as the starting point and now I want to authorize the home page's Index view, but now my MVC authorization attribute is not working and even using with authorization attribute I am able to directly open the Home page.
I need this to be authorized and then that authorized person should open the door to Angular application.
[Authorize]
public ActionResult Index()
{
return View();
}
and this is the Index View, and the starting point of my angularjs application, and other HTML pages are embedded in this view
<div class="row">
<div ng-view>
</div>
</div>
Kindly help me in solving this, and point me what I am doing wrong or I have implemented things wrong. Here is my HomeController's Index action with authorize attribute,

Try this
if you are using ui router you can add this to your app.js
.run(function($rootScope, $location) {
$rootScope.$on("$locationChangeStart", function(event,
next, current) {
if ($rootScope.authenticated == false)
//your code
});
})
For every location change you can check for authentication!

Related

Angularjs Does not work with Jquery load function

I am creating an web application using ASP.Net MVC5 and AngularJS 1.5, I have a page were data is display from MVC ActionResult and further Edit and Delete operation is perform using AngularJS.
But as I perform edit operation an jsonresult in call from ASP.net MVC controller and perform perfect edit operation with success result, but I also want to refresh the data that is display from MVC ActionResult so I created an partial view and use Jquery load function and pass the URL(MVC ActionResult Url).
The load function refresh the data with current changes in the database but after that AngularJS does not work even AngularJS {{Expressions}} are not working
$http.post('myactionName',{param:param}).success(function (data){
$('#DiV').load("mypartialActionName");
}
<div id="DiV">
#Html.Partial("_PartialViewName")
</div>
first add your jQuery and Angular files, then create the 'app' module
Html
<body configs>
<div id="DiV"> #Html.Partial("_PartialViewName") </div>
</body>
Directive
app.directive("configs", function($http){
return {
link: function(){
$http.post('myactionName',{param:param}).success(function (data){
$('#DiV').load("mypartialActionName");
}
}
}
});
First of all i want to say something if you are using completely AngularJs then do not use #Html.Partial()..use ng-include built in directive instead to inject external template..as of now you are totally depend on MVC that is the bad practice..you have to use MVC for only for server side not Front-end Part and AngularJs uses $http asynchronously you do not have to refresh to to retrieve your data and do not rely on JQUERY..AngularJs can tackle all the things whatever JQUERY did..

Navigating to new page from controller using AngularJS and Onsen UI

I have a cross platform app developed using Onsen UI, Monaca and AngularJS.
I am trying to navigate to a new page from a controller when the user clicks a button on my view. I am following a solution from THIS SO post but I keep getting the error: TypeError: Cannot read property 'pushPage' of undefined at Scope.$scope.getDateAndPushPage
I have my view set up to display a listview of dates using ng-repeat and when the user clicks on any of the listview items, I get the selected date item and and use it in my controller to perform some calculations. Once this is done I need to segue to the next page to display the calculations.
My listview looks as follows and displays the list of dates stored in data:
<ul class="list">
<li ng-repeat="myDate in data" class="list__item list__item--chevron" ng-click="getDateAndPushPage(myDate.date)")>
{{myDate.date}}
</li>
</ul>
In my views controller I try and push the new page as with the the example mentioned above as per my code below:
var dateReports = angular.module("dateReportsController", []);
dateReports.controller("DateReportsController", function($scope, $http, $rootScope)
{
$scope.getDateAndPushPage = function (myDate)
{
var page = "date-report-details.html";
console.log("Page: " + page); // OK here - outputs page: date-report-details.html
console.log("My Date: " + myDate); // OK here and do calculation
$rootScope.ons.myNavigator.pushPage(page); // Error here
}
});
And finally in my index.html I have my navigator defined as:
<!DOCTYPE HTML>
<html ng-app="myApp">
<head>
<!-- Usual content goes here - omitted because not relevant -->
</head>
<body>
<!-- The first page in the navigation stack -->
<ons-navigator var="myNavigator" page="login.html"></ons-navigator>
</body>
</html>
I have tried all the solutions offered on the above mentioned SO post but none seems to be working for me. I have my app setup in such a way that all controllers are split into their separate files to make it easier to manage. To this effect my main app.js file looks as follows and Im not sure is this where the issue is coming from
var app = angular.module("myApp", ['onsen', 'loginController', 'dateReportsController']);
your code is not able to find myNavigator variable. Try changing :
<ons-navigator var="myNavigator" page="login.html"></ons-navigator>
to <ons-navigator id="myNavigator" page="login.html"></ons-navigator>
and use: $rootScope.ons.$get('#myNavigator').pushPage(page);
To navigate to from page to another page, you can use the following code.
HTML
<ons-navigator var="myNavigator" page="page1.html"></ons-navigator>
In controller
$rootScope.myNavigator.pushPage('page2.html');

Angular.js - How to load different menu

I 'm starting jquery migrating an application to angular, but it has made ​​me a bit complex. I need to know if someone could help me as routing and load controllers, when login any user. There are two types of users
Students
Teachers
Each has a different menu , which in turn has different html pages. Depending on the role the user to enter then load the specific menu.
Using the jQuery load event , and changed the content which changes within a div . I would like to know how to perform this process with angular .
index.html
<html>
<head> Files ... </head>
<body>
<div id="container"></div>
</body>
</html>
student-menu.html
<div>
<div>option-1</div>
<div>option-2</div>
<div>option-3</div>
<div>option-N</div>
</div>
students-pages
option-1.html
option-2.html
option-3.html
option-N.html
teacher-menu.html
<div>
<div>option-1</div>
<div>option-2</div>
<div>option-3</div>
<div>option-N</div>
</div>
teachers-pages
option-1.html
option-2.html
option-3.html
option-N.html
Appreciate a clear explanation.
Please consider reading about including ui-router in your amazing application and learn about templateProviderusage.
As soon as you done with above things all you need is:
Create Service that will have getCurrentUserStatus() that should acquire from loaded data about user his status in your system
Depending on status configure your child views: { 'menu': { ... } } with
//somewhere above
const TEMP = {
user: 'path/to/file.tpl.html',
admin: 'path/to/admin.tpl.html'
}
//somewhere in view configuretion
...,
templateProvider (AuthService) {
return TEMP[AuthService.getCurrentUserStatus()];
},
...
Create all another pages with totally same approach of choosing needed template.
P.S. This allows you to expand list of variable templates unless your imagination will empty :D
P.P.S. Noobs way - lot of ng-include with ng-if on every view that will be changed depending on viewer.

Fancy box with mvc partial view issue

This is the message I get everytime I click the edit button:
The requested content cannot be loaded.
Please try again later.
Anyone have any ideas? If you need to see the partial view I can post it.
My Conbtroller:
[HttpPost]
public ActionResult SearchEdit(int modelcount)
{
using (Offers.OffersClient o = new Offers.OffersClient())
{
var offers = (List<Offers.Offer>)Session["offer"];
var offer = offers[modelcount];
return PartialView("Search_Edit", offer);
}
}
My View:
<div class="offer_edit">
<a href="#Url.Action("SearchEdit","Home",null,"http")?modelcount=#(i)" class="fancybox">
<img title="Edit" src="../images/edit_button.png" />
</a>
</div>
Your action is decorated with the [HttpPost] attribute. This means that this controller action can only be invoked using the POST verb. But in your view you are using a link (<a>) which when clicked sends a GET request unless you have configured the fancybox to use POST. To further investigate the issue you could use a javascript debugging tool such as FireBug to inspect the AJAX request being sent to the server as well as the response.

ASP.NET MVC 2.0 Ajax call - LoadingElementId not re-hidden when OnSuccess script specified

I'm writing a very simple web application in ASP.NET MVC 2.0 which is used as a test interface for a web service. The various pages present a user interface to input the parameters for the request messages. The parameters are submitted back to the controller via Ajax, which returns a partial view containing the response SOAP message (HTML encoded XML) in a <pre> tag...
// In controller...
ActionResult WebMethodTest()
{
return View(new WebMethodModel());
}
[HttpPost]
ActionResult WebMethodTest(WebMethodModel model)
{
model.Response = MyServiceProxy.WebMethod(model.Request);
return PartialView("SoapResponse", model.Response);
}
// In view
<% using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId="Response", LoadingElementId="Loading", HttpMethod="POST", OnSuccess="prettyPrint"}))
{ %>
<!-- various model bound controls... -->
<% { %>
<div id="Loading" style="text-align:center; display:none">
<img src="../../Content/ajax-loader.gif" alt="loading..." /><br />
working...
</div>
Unfortunately the Loading div element is not being hidden again when the data is returned after the Ajax call, it stays visible. Interestingly, it does get hidden correctly if I remove OnSuccess="prettyPrint". I get the impression that my OnSuccess script is overriding the default behaviour, rather than executing in addition. I don't want to lose prettyPrint though as it's colourizing the XML which is being displayed... how can I keep the default loading element behaviour as well as my own OnSuccess hook?
Cheers!
I resolved this issue by amending the OnSuccess script to this:
OnSuccess = "function() { prettyPrint(); return true; }"
So it seems that, like OnBegin, returning false (or anything other than true) cancels the operation, although by this stage the DOM has already been updated, so the only thing you can canel is hiding the Loading element... which doesn't seem terribly useful!

Categories