Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS with ServiceStack/WebApi/MVC Actions

I am new to AngularJS and want to use it for our new project based on ASPNET MVC. I want AngularJS to manage the views ( it will be hybrid SPA, some pages normal MVC generated views). But I am in fix to decide what should I choose at the server end. i.e. ServiceStack/WebApi/MVC Actions ? There are examples in the web for WebAPI and regular ASPNET MVC, but couldn't find any SS+Angular examples. Could you give me an example project with SS+Angular( how to manage routing, prevent the views( html files) from opening directly by the user etc).

like image 582
jeff Avatar asked Sep 04 '13 19:09

jeff


People also ask

How do I use Web API in MVC with angular?

Create a MVC 4 application. Add a WEB API. Use AngularJs to consume WEB API. Perform the CRUD (Create, Read, Update & Delete) operations using Angular with WEB API. AngularJS is a structural framework for dynamic web apps.

What is the difference between MVC and angular?

Anugular is very close to MVC and MVVM but Angular has been declared as MVW pattern where "W" stand for "Whatever" (whatever works for you). Basically, Angular has three components as shown below:

What is the action method in the web API controller?

Inside this Action method, simply the View is returned. The Web API Controller consists of the following four Action methods. Inside this Action method, all the records from the Customers table is returned to the View as a Generic List collection.

Is there any server side view code in Angular JS?

In Angular JS, there will be no any server side view code. Beauty of this framework is without refresh of the complete page, we can inject the data to the view (add, modify and delete the HTML data without refreshing the page).


2 Answers

A few months back I put together a Demo project (https://github.com/paaschpa/ordersDemo) for Chicago Code Camp 2013. The sample site on AppHarbor seems to be down (I got the AppHarbor site working but all my 'production configs' are in the GitHub repo. I can never get the config/settings right between GitHub and them) but I think the code resembles what you're asking for. It uses AngularJS (probably not the best example of it), .NET MVC w/ServiceStack hosted at /api. It also uses Twitter BootStrap, Redis Pub/Sub and SignalR...probably smashed too much stuff into this project/example. If you can get Redis installed (https://github.com/dmajkic/redis/downloads) and you change the redisUrl to localhost:6379 in the web.config file you should be able to get it running locally.

like image 163
paaschpa Avatar answered Oct 09 '22 19:10

paaschpa


I use ServiceStack + ASP.NET MVC + Angular in my project.

Once ServiceStack installed (pretty easy with nugget package), call ServiceStack Rest WS is very simple with angular in a service:

GetById: function (movieId) {
    var url = root + 'api/movie/' + movieId;
    var promise = $http({ method: 'GET', url: url }).then(function (response) {
        return response.data;
    });

    return promise;
}, ...

In ServiceStack I Use DTO and ViewModel like this :

#region MovieDTO
[Api("GET Movie by Id")]
[Route("/movie/{Id}")]
public class MovieDTORequest
{
    public int Id { get; set; }
}

public class MovieDTOResponse
{
    public MovieViewModel Movie{ get; set; }
}

#endregion

And to finish my service :

private MovieBusiness _movieBusiness= (MovieBusiness )UnityHelper.BusinessResolve<Movie>();
public object Get(MovieDTORequest request)
{
    Movie movie = _movieBusiness.GetById(request.Id);
    MovieViewModel movieViewModel = MovieAdapter.ToViewModel(movie);

    return new MovieDTOResponse { Movie = movieViewModel };
}

Concerning routing, in my cas I use ASP.NET MVC route because I am more comfortable with it. So I have created a BaseController sending ServiceStack User to each View:

[ProfilingActionFilter]
public class BaseController : ServiceStackController<CustomUserSession>
{
    /// <summary>
    /// Surcharge de l'action pour charger la notification dans le ViewBag s'il y en a une et l'a marquer comme delivrée
    /// </summary>
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);
        int Id = 0;
        UserViewModel user= new UserViewModel ();

        if (int.TryParse(base.UserSession.UserAuthId, out Id))
        {
            user= new UserViewModel ()
            {
                id = Convert.ToInt32(base.UserSession.UserAuthId),
                nom = base.UserSession.DisplayName,
                roles = base.UserSession.Roles != null ? string.Join(",", base.UserSession.Roles.ToArray()) : string.Empty
            };
        }
        ViewBag.User= user;
    }

Next if you need to pass a ViewModel direcly to a angular Controller you can do this :

@model AddictLive.Core.ViewModel.Mobile.ViewModels.MovieViewModel
@using Newtonsoft.Json

<div ng-controller="MovieController" ng-init="init(@Html.Raw(JsonConvert.SerializeObject(Model)))">
     ...
</div>

Sample of init() method in the angular controller :

$scope.init = function (movieViewModel) {
    $scope.property1= movieViewModel.property1;
    $scope.property2= movieViewModel.property2;
};

I simplified all my examples to make it easy to understand but if you need more explanation let me know

like image 27
toregua Avatar answered Oct 09 '22 19:10

toregua