Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to communicate between angularjs and mvc5?

I've some confusions to transfer data between angularjs and MVC5. I am creating single page application (SPA).

  1. What is the best way to work with angularjs? Is MVC controllers or MVC APIs ?.
  2. I read it here that api's are good for SPA. So, do I need to build a different project for APIs ?
  3. What about asynchronous communication for Angularjs with MVC ?

I am not getting a right direction to work ahead. I am familiar with mvc but not APIs. So, Please guid me a right way !!

Thanks in advance

like image 891
Sarbanjeet Avatar asked Mar 17 '23 10:03

Sarbanjeet


1 Answers

First of all, with the current version of Visual Studio (2013) there's no distinction between a "web form" project and an "mvc" project. There's just a web application project and inside you can put whatever you want.

Now from my experience a nice and clean way to approach your problem is to create normal MVC controllers to render the razor views that contain the angularJS application(s), and to create WebAPI controllers for the RESTful interface for the ajax methods.

In angularJS you don't really need to manually do your ajax calls. There is a more convenient and powerful way: resources. They also play well with the WebAPI design, since a WebAPI controller works with a single type of object (i.e. a customer) and through HTTP VERBS allows you to do the CRUD. For instance:

// assume we have a backend repository that handles the data

public HttpResponseMessage Get()
{
    return this.Request.CreateResponse(HttpStatusCode.OK, this.repository.GetAllCustomers()); 
}

public HttpResponseMessage Post(Customer customer)
{
    var modifiedCustomer = this.repository.Update(customer);
    this.repository.SaveChanges();

    return this.Request.CreateResponse(HttpStatusCode.OK, modifiedCustomer);
}

This method queries all the available customers and returns them. You don't define here whether to return JSON or XML: the WebAPI framework reads the HTTP HEADERS of the WebAPI request and serializes the data as requested from the client. For JSON, which you'll be likely be using, it does the serialization through the default JSON serializer defined. You can override this to change the way JSON is created, a common way is to use JSON.NET with custom settings.

AngularJS resources are made to map a single URL and work with all the verbs internally and expose you methods like $save, $query, $get and so forth, so they couple up very well. For instance:

var customerRes =  $resource('/customers');
var currentCustomers = customerRes.query(function(){ // query is mapped to the GET verb
    currentCustomers[0].email = "[email protected]";
    currentCustomers[0].$save(); // default mapped to the POST verb
});

I suggest you to check the documentation and samples for more details.

like image 197
Matteo Mosca Avatar answered Apr 02 '23 17:04

Matteo Mosca