Friday, August 7, 2015

AngularJS – Load drop down list from sql (API)

I have a lookup table in SQL with the values I need in the drop down list.



Starting with:
  1. Lookup Model
    namespace MyWeb.Models
    {
    public class Lookups
    {
    #region Instance Properties
    public Int32 ID { get; set; }
    public string LookupType { get; set; }
    public string LookupKey { get; set; }
    public string LookupValue { get; set; }
    #endregion Instance Properties
    }
    }
    view raw MyWebModel.cs hosted with ❤ by GitHub

  2. WebApiConfig.cs in App_Start
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Http;
    namespace MyWeb
    {
    public static class WebApiConfig
    {
    public static void Register(HttpConfiguration config)
    {
    config.MapHttpAttributeRoutes();
    config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
    );
    }
    }
    }


Steps:
  1. Create an API controller
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;
    using System.Web.Http.Description;
    using MyWeb.Models;
    namespace MyWeb.Controllers
    {
    public class LookupsAPIController : ApiController
    {
    private ApplicationDbContext db = new ApplicationDbContext();
    // GET: api/LookupsAPI
    public IQueryable<Lookups> GetLookups()
    {
    return db.Lookups;
    }
    protected override void Dispose(bool disposing)
    {
    if (disposing)
    {
    db.Dispose();
    }
    base.Dispose(disposing);
    }
    }
    }

    I'm using Entity Framework, so I right clicked on Controllers, Add, Controller. I then selected Web API 2 Controller with acitons.



  2. Override the routing to create a different type of call
    // GET: api/LookupsAPI/State
    [Route("api/getLookupsAPI/{LookupType}")]
    public IQueryable<Lookups> GetLookupsByType(string LookupType)
    {
    return db.Lookups.Where(lookup => lookup.LookupType == LookupType);
    }

    *** Great overview of Custom Routing - http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2


  3. Create SetLookups function in the AngularJS controller script
    function SetLookups($scope, $http) {
    // Create drop down lists
    $http({ method: 'GET', url: 'api/getLookupsAPI/States' }).
    success(function (data) { $scope.States = data; }).
    error(function (data) { alert('did not get states'); });
    }
    view raw MyWebLookups.js hosted with ❤ by GitHub


  4. Call SetLookups from AngularJS controller
    app.controller('IncidentEditController',['$scope', '$filter', '$http', '$routeParams','$location','ClaimsAPI', function ($scope, $filter, $http, $routeParams, $location, ClaimsAPI) {
    $scope.editClaim = this;
    var claimId = $routeParams.id;
    // Prep for the drop down fields
    SetLookups($scope, $http);
    ClaimsAPI.getClaim(claimId)
    .success( function ( incs ) {
    $scope.editClaim.Claim = incs;
    $scope.status = incs.ID;
    })
    .error( function ( error ) {
    $scope.status = 'Unable to load customer data: ' + error.message;
    });
    $scope.editClaim.destroy = function () {
    ClaimsAPI.deleteClaims( claimId ).then( function ( data ) {
    $location.path('/');
    });
    };
    $scope.editClaim.save = function () {
    $scope.$broadcast('show-errors-check-validity');
    if ($scope.myForm.$valid) {
    ClaimsAPI.updateClaim($scope.editClaim.Claim).then(function (data) {
    $location.path('/');
    });
    }
    };
    });
    }]);


  5. Create Select tab using ng-options to load
    <div class="row">
    <div class="form-group col-xs-6">
    <label class="control-label col-xs-4">State</label>
    <div class="col-xs-8">
    <select ng-model="editClaim.Claim.State" ng-options="state.LookupKey as state.LookupValue for state in States"></select>
    </div>
    </div>
    <div class="form-group col-xs-6">
    <label class="control-label col-xs-4">Zip</label>
    <div class="col-xs-8">
    <input type="text" ng-model="editClaim.Claim.Zip" placeholder="99999-9999">
    </div>
    </div>
    </div>

1 comment: