In this blog, we will learn how to build a simple CRUD (Create, Read, Update, Delete) application using ASP.NET Core as the backend and AngularJS as the frontend.

We will perform CRUD operations on a table called CountryMaster, which contains the following fields:

  • CountryCode – A short code that represents the country (like "IN" for India, "US" for the United States).

  • CountryName – The full name of the country (like "India", "United States").

     What We'll Do:

  • Create a Web API in ASP.NET Core to handle backend operations. we have already made this -  To read visit at  crud-operations-in-asp-dot-net-core-using-entity-framework

  • Build a simple AngularJS frontend to call the API and show the data on the screen.

  • Add form validation to make sure the data entered is correct.

  • Handle errors properly so the user knows if something goes wrong.

    Features:

  • Add Country – Save new country details.

  • View Country List – Show a list of all countries.

  • Update Country – Edit country details.

  • Delete Country – Remove a country from the list.

Step : Add a file with extension of .htm or .html for writing the code of Angular JS and html etc.
Note : we need below CDN to work with Bootstrap and Angular JS 

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script><!--Angular js-->

<!DOCTYPE html>
<html ng-app="countryApp">
<head>
  <meta charset="UTF-8">
  <title>Country Manager</title>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script><!--Angular js-->
</head>
<body ng-controller="CountryController" class="container mt-4">
<!-- Loader -->
<div ng-show="loading" class="text-center my-3">
    <div class="spinner-border text-primary" role="status">
      <span class="sr-only">Loading...</span>
    </div>
    <p class="mt-2">Processing...</p>
  </div>
  <h2>Country Management</h2>

  <!-- Message Alert -->
  <div class="alert alert-{{alertType}}" ng-if="message">
    {{message}}
  </div>

  <!-- Country Form -->
  <form name="countryForm" ng-submit="submitCountry()" novalidate>
    <input type="hidden" ng-model="country.countryId" />
    <div class="form-row">
      <div class="form-group col-md-4">
        <label>Country Code</label>
  <input type="text" class="form-control" id="txtCountryCode" ng-model="country.countryCode" required>
      </div>
      <div class="form-group col-md-4">
        <label>Country Name</label>
        <input type="text" class="form-control" id="txtCountryName" ng-model="country.countryName" required>
      </div>
      <div class="form-group col-md-4 align-self-end">
        <button type="submit" class="btn btn-primary" >
          {{ isEditing ? 'Update' : 'Submit' }}
        </button>
        <button type="button" class="btn btn-secondary" ng-click="resetForm()">Refresh</button>
      </div>
    </div>
  </form>

  <!-- Country Grid -->
  <table class="table table-bordered table-striped mt-4">
    <thead class="thead-dark">
      <tr>
        <th>Sr. No</th>
        <th>Country Code</th>
        <th>Country Name</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="c in countries track by $index">
        <td>{{$index + 1}}</td>
        <td>{{c.countryCode}}</td>
        <td>{{c.countryName}}</td>
        <td>
          <button type="button" class="btn btn-sm btn-info" ng-click="editCountry(c)">Edit</button>
          <button type="button" class="btn btn-sm btn-danger" ng-click="deleteCountry(c)">Delete</button>
        </td>
      </tr>
    </tbody>
  </table>

  <script>
    var app = angular.module('countryApp', []);
    app.controller('CountryController', function ($scope, $http) {
      const apiBase = 'http://localhost:5144/api/Home';
 
      $scope.countries = [];
      $scope.country = {};
      $scope.isEditing = false;
      $scope.message = '';
      $scope.alertType = 'success';
      $scope.loading = false;
 
      // Load data
      $scope.loadCountries = function () {
        $scope.loading = true;
        $http.get(apiBase + '/GetCountry').then(function (res) {
          $scope.countries = res.data;
        }, function () {
          $scope.showMessage("Error loading countries", 'danger');
        }).finally(() => {
          $scope.loading = false;
        });
      };
 
      // Submit or update
      $scope.submitCountry = function () {
        if (!$scope.country.countryCode) {
            $scope.showMessage("Country Code is required.", 'warning');
            document.getElementById('txtCountryCode').focus();
            return;
        }
        if (!$scope.country.countryName) {
            $scope.showMessage("Country Name is required.", 'warning');
            document.getElementById('txtCountryName').focus();
            return;
        }
        $scope.loading = true;
        if ($scope.isEditing) {
          $http.put(apiBase + '/UpdateCountry', $scope.country).then(function (res) {
            $scope.showMessage(res.data.message, 'success');
            $scope.resetForm();
            $scope.loadCountries();
          }, function () {
            $scope.showMessage("Update failed", 'danger');
          }).finally(() => {
            $scope.loading = false;
          });
        } else {
          $http.post(apiBase + '/SetCountry', $scope.country).then(function (res) {
            $scope.showMessage(res.data.message, 'success');
            $scope.resetForm();
            $scope.loadCountries();
          }, function () {
            $scope.showMessage("Submit failed", 'danger');
          }).finally(() => {
            $scope.loading = false;
          });
        }
      };
 
      // Edit
      $scope.editCountry = function (country) {
        $scope.country = angular.copy(country);
        $scope.isEditing = true;
      };
 
      // Delete
      $scope.deleteCountry = function (country) {
        if (confirm("Are you sure to delete " + country.countryName + "?")) {
          $scope.loading = true;
          $http({
            method: 'DELETE',
            url: apiBase + '/DeleteCountry',
            data: country,
            headers: { 'Content-Type': 'application/json' }
          }).then(function (res) {
            $scope.showMessage(res.data.message, 'success');
            $scope.loadCountries();
          }, function () {
            $scope.showMessage("Delete failed", 'danger');
          }).finally(() => {
            $scope.loading = false;
          });
        }
      };
 
      // Reset form
      $scope.resetForm = function () {
        $scope.country = {};
        $scope.isEditing = false;
        $scope.countryForm.$setPristine();
        $scope.countryForm.$setUntouched();
      };
 
      // Message handler
      $scope.showMessage = function (msg, type) {
        $scope.message = msg;
        $scope.alertType = type;
        setTimeout(() => $scope.$apply(() => $scope.message = ''), 3000);
      };
 
      // Initial load
      $scope.loadCountries();
    });
  </script>

</body>
</html>


Output :

Let's understand given above code :

1. HTML Structure & AngularJS Setup

<!DOCTYPE html>
<html ng-app="countryApp">
  • Declares AngularJS application using ng-app="countryApp".


2. Head Section – Dependencies

<head>
    <meta charset="UTF-8">
    <title>Country Manager</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
  </head>
  • Loads Bootstrap for styling.

  • Loads AngularJS v1.8.2.


3. Loader Spinner

<div ng-show="loading" class="text-center my-3">
    <div class="spinner-border text-primary" role="status">
      <span class="sr-only">Loading...</span>
    </div>
    <p class="mt-2">Processing...</p>
  </div>
  • Displays a loading spinner when loading is true.


4. Heading & Message Box

<h2>Country Management</h2>
<div class="alert alert-{{alertType}}" ng-if="message">
  {{message}}
</div>
  • Shows a status message (e.g., success, danger) when message is set.


5. Country Input Form

<form name="countryForm" ng-submit="submitCountry()" novalidate>
    <input type="hidden" ng-model="country.countryId" />

Fields:

  • countryCode – required

  • countryName – required

Buttons:

  • Submit (or Update if editing)

  • Refresh resets the form

<button type="submit" class="btn btn-primary">
    {{ isEditing ? 'Update' : 'Submit' }}
  </button>
  <button type="button" class="btn btn-secondary" ng-click="resetForm()">Refresh</button>

6. Country Grid (Table View)

<table class="table table-bordered table-striped mt-4">
  • Displays a list of countries using ng-repeat

  • Each row shows:

    • Sr. No.

    • Country Code

    • Country Name

    • Edit/Delete buttons


7. AngularJS App and Controller (CountryController)

var app = angular.module('countryApp', []);

Main Variables:

  • countries – list of countries

  • country – current form data

  • isEditing – flag for form state

  • messagealertType – for status messages

  • loading – for spinner


8. Key Functions

Load Country Data

$scope.loadCountries = function () {
    $http.get(apiBase + '/GetCountry')
  }

Submit or Update Country

$scope.submitCountry = function () {
  if ($scope.isEditing) {
    $http.put(apiBase + '/UpdateCountry', $scope.country)
  } else {
    $http.post(apiBase + '/SetCountry', $scope.country)
  }
}

Edit Country

$scope.editCountry = function (country) {
  $scope.country = angular.copy(country);
  $scope.isEditing = true;
}

Delete Country

$scope.deleteCountry = function (country) {
  $http({
    method: 'DELETE',
    url: apiBase + '/DeleteCountry',
    data: country,
    headers: { 'Content-Type': 'application/json' }
  })
}

Reset Form

$scope.resetForm = function () {
  $scope.country = {};
  $scope.isEditing = false;
  $scope.countryForm.$setPristine();
  $scope.countryForm.$setUntouched();
}

Show Message

$scope.showMessage = function (msg, type) {
  $scope.message = msg;
  $scope.alertType = type;
  setTimeout(() => $scope.$apply(() => $scope.message = ''), 3000);
}


Leave a Reply

Your email address will not be published. Required fields are marked *


Talk to us?

Post your blog

F.A.Q

Frequently Asked Questions