Understanding of a front-end AngularJS, back-end OData, ASP. NET Web API case, angularjsodata

Source: Internet
Author: User
Tags toastr

Understanding of a front-end AngularJS, back-end OData, ASP. NET Web API case, angularjsodata

 

Still chsakell, he wrote a front-end AngularJS, back-end OData, ASP. NET Web API Demo, about OData in ASP. there is nothing special about the forward deletion, modification, and query of Web APIs. However, when calling APIs on the frontend, It is of reference to encapsulate $ resouce in a service.

 

Article: http://chsakell.com/2015/04/04/asp-net-web-api-feat-odata/
Source code: https://github.com/chsakell/odatawebapi

 

The first is the domain model.

 

public class Employee{    public int ID{get;set;}        ...    public int AddressID { get; set; }    public virtual Address Address { get; set; }    public int CompanyID { get; set; }    public virtual Company Company { get; set; }}public class Address{    public int ID{get;set;}    ...}public class Company{    public int ID{get;set;}        ..    public virtual List<Employee> Employees{get;set;}        public Compay()    {        Employees = new List<Employee>();    }}

 

Use the EF Fuent API to configure the domain and inherit EntityTypeConfiguration <T>, for example:

 

public class CompanyConfiguration: EntityTypeConfiguration<Company>{}

 

The context inherits from DbContext.

 

public class EntitiesContext : DbContext{}

 

The seed data inherits from DropCreateDatabaseIfModelChanges.

 

public class EntitiesInitializer : DropCreateDatabaseIfModelChanges<EntitiesContext>{}

 

Configure the project connection string.

 

<connectionStrings>  <add name="EntitiesContext" providerName="System.Data.SqlClient" connectionString="Server=(localdb)\v11.0; Database=CompanyDB; Trusted_Connection=true; MultipleActiveResultSets=true" /></connectionStrings>

 

Enable the configuration of seed data in the global file of the project.

 

protected void Application_Start(){    GlobalConfiguration.Configure(WebApiConfig.Register);    // Init the database    Database.SetInitializer(new EntitiesInitializer());}

 

Enter odata in NuGet to install V4.0.

 

For more information about adding, deleting, modifying, and querying ODataController, see ASP. NET Web API is based on OData to add, delete, modify, and query, and process the relationship between entities. This section describes in detail, and focuses on front-end calls.

 

First, let's look at the interface:

 

 

The main view is as follows:

 

<Html ng-app = "mainApp"> 

 

In general, there are multiple front-end operations for a certain field. One of chsakell's writing methods is particularly recommended, that is, the operations for a specific field are in AngularJS, encapsulate $ resource into a service. As follows:

 

angular.module('mainApp')    .factory('employeeService', function ($resource) {        var odataUrl = '/odata/Employees';        return $resource('', {},            {                'getAll': { method: 'GET', url: odataUrl },                'getTop10': { method: 'GET', url: odataUrl + '?$top=10' },                'create': { method: 'POST', url: odataUrl },                'patch': { method: 'PATCH', params: { key: '@key' }, url: odataUrl + '(:key)' },                'getEmployee': { method: 'GET', params: { key: '@key' }, url: odataUrl + '(:key)' },                'getEmployeeAdderss': { method: 'GET', params: { key: '@key' }, url: odataUrl + '(:key)' + '/Address' },                'getEmployeeCompany': { method: 'GET', params: { key: '@key' }, url: odataUrl + '(:key)' + '/Company' },                'deleteEmployee': { method: 'DELETE', params: { key: '@key' }, url: odataUrl + '(:key)' },                'addEmployee': { method: 'POST', url: odataUrl }            });    }).factory('notificationFactory', function () {        return {            success: function (text) {                toastr.success(text, "Success");            },            error: function (text) {                toastr.error(text, "Error");            }        };    })

 

Then, add or remove a controller in the mainApp to perform various operations on the Employee.

 

Angular. module ('mainapp '). controller ('apachetrl', function ($ scope, employeeService, icationicationfactory) {// store the current user $ scope. currentEmployee ={}; // Get Top 10 Employees $ scope. getTop10Employees = function () {(new employeeService ()). $ getTop10 (). then (function (data) {// store all users $ scope. employees = data. value; $ scope. currentEmployee = $ scope. employees [0]; // set the navigation attribute of Empoyee $ scope. setCurrentEmployeeAddress (); $ scope. setCurrentEmployeeCompany (); // notifies icationicationfactory. success ('ployeess loaded. ') ;};}; // Set active employee for patch update $ scope. setEmployee = function (employee) {$ scope. currentEmployee = employee; $ scope. setCurrentEmployeeAddress (); $ scope. setCurrentEmployeeCompany () ;}; // set the address of the current Employee $ scope. setCurrentEmployeeAddress = function () {// obtain the current Employee var currentEmployee = $ scope. currentEmployee; return (new employeeService ({"ID": currentEmployee. ID ,})). $ getEmployeeAdderss ({key: currentEmployee. ID }). then (function (data) {$ scope. currentEmployee. city = data. city; $ scope. currentEmployee. country = data. country; $ scope. currentEmployee. state = data. state ;}) ;}// set the Company $ scope of the current Employee. setCurrentEmployeeCompany = function () {var currentEmployee = $ scope. currentEmployee; return (new employeeService ({"ID": currentEmployee. ID ,})). $ getEmployeeCompany ({key: currentEmployee. ID }). then (function (data) {$ scope. currentEmployee. company = data. name ;}) ;}// Update Selected Employee $ scope. updateEmployee = function () {var currentEmployee = $ scope. currentEmployee; console. log (currentEmployee. email); if (currentEmployee) {return (new employeeService ({"ID": currentEmployee. ID, "FirstName": currentEmployee. firstName, "Surname": currentEmployee. surname, "Email": currentEmployee. email })). $ patch ({key: currentEmployee. ID }). then (function (data) {icationicationfactory. success ('employee with id' + currentEmployee. ID + 'updated. ')}) ;}$ scope. deleteEmployee = function () {var currentEmployee = $ scope. currentEmployee; return (new employeeService ({"ID": currentEmployee. ID ,})). $ deleteEmployee ({key: currentEmployee. ID }). then (function (data) {icationicationfactory. success ('employee with id' + currentEmployee. ID + 'removed. '); $ scope. getTop10Employees () ;}) ;}$ scope. addEmployee = function () {var newEmployee = $ scope. newEmployee; return (new employeeService ({"FirstName": newEmployee. firstName, "Surname": newEmployee. surname, "Email": newEmployee. email, "AddressID": 1, // normally obtained from UI "CompanyID": 3 // normally obtained from UI })). $ addEmployee (). then (function (data) {icationicationfactory. success ('Employee' + newEmployee. firstName + ''+ newEmployee. surname + 'added successfully '); $ scope. newEmployee = {};});}});

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.