asp.net filter equivalent in angularjs - asp.net-mvc

I would like to invoke a service method on the beginning of each controller in angularjs. Just like I would do with a filter in asp.net mvc or a middleware in express/nodejs.
How should I do this in angularjs ?

I found out how to go about doing this.
AngularJS provides events I can bind to.
$onRouteChangeStart and $onRouteChangeFinish
The first is triggered just before the route is changed, and the latter after (and after all dependencies are resolved for the controller).
So, in order to invoke code before each controller I would add something like this to my app:
var app = angular.module('MyApp', [...]);
app.run(['$rootScope', function($rootScope) {
$rootScope.$on('$routeChangeStart', function(event, target) {
// CODE GOES HERE
});
}]);

Related

Durandal not passing parameters to MVC controller action

I'm having a problem using parameters in Durandal for an ASP.NET MVC application...
I use MVC Route Attributes, for example:
[Route("admin/pages")], [Route("admin/blog")], etc..
And I integrate Durandal as follows:
main.js:
app.start().then(function() {
viewEngine.viewExtension = '/';
viewLocator.convertModuleIdToViewId = function (moduleId) {
return moduleId.replace('viewmodels', '');
};
app.setRoot('viewmodels/admin/shell', 'entrance');
});
This works nicely, as the viewId ends up matching the MVC route.
However, I now face a serious problem with trying to use parameters in the routes. For example, I have one route as follows:
[Route("admin/localization/localizable-strings/{languageId}")]
and my Durandal route for this is:
localization/localizable-strings/:languageId
Example anchor tag:
Localize
This doesn't work, as it seems Durandal doesn't pass the parameter to the server. It simply retrieves the HTML from /admin/localization/localizable-strings which returns a 404 page because no parameter was passed to the MVC action.
What are my options here?
I know this question is almost 2 years old now, but I obviously forgot to close it with my solution at the time. Basically, Brett and Marvin were correct, but since I was so new to Durandal (and SPAs in general) at the time, I misunderstood exactly what they were telling me. I ended up doing this:
self.cultureCode = null;
self.activate = function (cultureCode) {
self.cultureCode = cultureCode;
if (!self.cultureCode) {
self.cultureCode = null;
}
};
And the durandal route was set up as follows;
"localization/localizable-strings/:cultureCode"
I would then use that parameter to obtain the relevant data via ajax. My mistake was wanting the parameter to be able to be used in the MVC action method so that I could obtain some data server side, which of course doesn't work...

AngularJs Search form with WebApi

I am new to angularjs so I may be taking the wrong approach but here is my situation. I have an MVC3 app but I am only using Mvc to serve up a "layout" page and the script and css files. In that view I have a ng-view tag. Here is my routeProvider
$routeProvider.when('/', { templateUrl: '/templates/search.html', controller: 'SearchController' }).
when('/Search', { templateUrl: '/templates/searchResults.html', controller: 'SearchController' });
So initially the search.html template is going to load which is nothing but a form and Search button. The user enters whatever form data they want to search by and click "Search" which is tied to a function $scope.search that gets the form data and call WebApi to get the results. The function returns a promise, and .then I want to assign the results to the $scope and then load the searchResults.html template by calling $location.path("/Search"); The problem is when that is called it reloads the controller and the $scope is wiped out.
I want to do this without using the MVC framework. I know angular takes a new way of thinking and I think my problem lies there. Can anyone guide me to where I should be going with this?
You do not need to call the $location.path("/Search");.
Hide the tag in which you need to show the search results using ng-hide and show it when the promise is executed.

Callinf action in controller via jquery

I am new to MVC and I am continuing to learn more each day. I am converting and webform application to MVC for practice and wanted to know is there a way to call GET on a action and return json, array or whatever I want on document.ready function? I can do this using webapi, but I would rather do it using an action in the controller. I like the helpers that they Microsoft provides but they are for forms and action links, etc. Thanks for any help.
$(document).ready(function(){
$.ajax(Somehow call controller action here with data), success(function that returns json data)
});
I think this article has a great explanation with examples
http://www.codeproject.com/Articles/41828/JQuery-AJAX-with-ASP-NET-MVC

Is there a clean way to embed a url in a razor view?

I have a partial view in an ASP.NET MVC app:
#Html.Partial("_Comments", Model)
I want to make this partial a "plugin" that can be called from other apps. So, I created a separate action in my controller to return this partial view alone:
public ActionResult Embed()
{
return View("_Comments", new CommentsModel());
}
This action can then be accessed via the URL [root]/Comments/Embed and returns the partial view's HTML.
Is there a clean way to embed the response from this URL in a separate MVC razor view (in an entirely different app)?
Thanks!
Is there a clean way to embed the response from this URL in a separate MVC razor view (in an entirely different app)?
This means client side code, for example:
function getComments() {
$.ajax({ url: '[root]/Comments/Embed',
iframe: true,
success: function (data) {
$("#target-id").html(data);
}
});
}
Edit
In case you use this ajax plugin, if you set
iframe: true
then you access cross domain by iframe transparenlty
I found a solution.
#Html.Raw(new WebClient().DownloadString("[root]/Comments/Embed"))

Can ASP.NET MVC return a javascript response like Ruby on Rails can?

I'm diving into ASP.NET MVC and I'm coming from a Ruby on Rails background. I'm trying to understand how ASP MVC handles AJAX functionality and, after reading some of the tutorials on the ASP website, it appears they implement AJAX functionality very differently. One of the ways that RoR handles AJAX functionality is by returning ruby-embedded javascript code that is executed as soon as it is received by the browser. This makes implementing AJAX really simple and quite fun. Can ASP.NET MVC return a javascript response?
just user
return JavaScript(script)
You would have to execute the java script manually on the View
To be more specific you can make the controller action return type JavaScriptResult
What you are talking about is called javascript generators in the RoR world and there's no equivalent in the ASP.NET MVC world. Here's a blog post that illustrates the basics of implementing a Rails-like RJS for ASP.NET MVC (the blog post uses prototypejs but could be easily adapted to work with jquery).
Here's another approach using jquery:
public ActionResult Foo()
{
return Json(new { prop1 = "value1", prop2 = "value2" });
}
and to consume:
$.getJSON('/home/foo', function(result) {
// TODO: use javascript and work with the result here,
// the same way you would work in a RJS like template
// but using plain javascript
if (result.prop1 === 'value1') {
alert(result.prop2);
}
});
Also worth taking a look at is JsonResult which extends ActionResult. I usually use this when making AJAX requests for data of some sort.

Resources