What is the best way to communicate between angularjs and mvc5?

I have some confusion for transferring data between angularjs and MVC5. I am creating a single page application (SPA).

  • What is the best way to work with angularjs? Are MVC controllers or MVC APIs ?.
  • I read here that api are good for SPA. So, do I need to create another project for the API?
  • What about asynchronous communication for Angularjs with MVC?

I am not getting the right direction to move forward. I am familiar with mvc, but not with the API. So please introduce me the right way.

Thanks in advance

+4
source share
3 answers

, Visual Studio (2013) "-" "mvc". - , .

, , - MVC- , angularJS, WebAPI RESTful ajax.

angularJS -. : . WebAPI, WebAPI ( ), HTTP VERBS CRUD. :

// 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);
}

. , JSON XML: WebAPI HTTP-HEADERS WebAPI . JSON, , , , JSON-. , JSON, - JSON.NET .

AngularJS URL- , $save, $query, $get .., . :

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

.

+4

MVC API Async MVC. Async , API . Async . , API .

, , MVC API- , .. 1. . 2. IIS. , API Async .

+2

1) Simple Controller - , JsonResult Angular AJAX

2) Yes - if you want to build API- you need to create a new type of project WebAPi(now it is v 2.0), but you can create it in one solutionusing SPA

3) You can call AJAX asynchronous- this is not a problem

+1
source

Source: https://habr.com/ru/post/1570556/


All Articles