Click here to Skip to main content
15,860,972 members
Articles / Programming Languages / C#

Sample MVC, AngularJs with WebAPI to Update DB

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
5 Oct 2017CPOL1 min read 15.3K   5   2
Example for database Update and Insert using Angular, Web APIs

Introduction

This article explains how to update and insert a database table using Angular JS, Web API, Entity Framework in MVC in simple steps.

Background

There are many articles that couldn't explain how to do database updates using technologies combination of MVC, AngularJS , Web APIs. I have created a sample project to explain how simple to use the AngularJS with Web APIs.

Using the Code

Step 1

Create a MVC Website in Visual Studio.

Step 2

Create database with a table name ‘Question’ with fields QuestionId, QuestionText.

Create Entity Framework .edmx file with db context name as DBcontext. Add Question table into the project. After generating the EF class into project, the Question model class looks like below:

C#
public partial class Question 
{       
   public int QuestionId { get; set; } 
   public string QuestionText { get; set; }
}

Step 3

Add the Web API Controller to the Project as shown in screen 1:

Image 1

  • Create Action Methods, GetQuestion(), AddQuestion(), UpdateQuestion() database, these Actions returnJsonResult.
  • QuestionAdmin() which calls the View. This Action invokes the UI.

Controller class code looks like below:

C#
public class QAdminController : Controller 
{       
        //Create Entity Framework Database context object
        DatabaseConnection DBcontext = new DatabaseConnection();       
   
       //Call View to Display records in UI
       public ActionResult QuestionAdmin()
       {
           return View();
       }

       //Get Question
       public JsonResult GetQuestion()
       {
           var questions = (from q in DBcontext.Questions select new Question   
                           { QuestionId = q.QuestionId, 
                              QuestionText = q.QuestionText 
                           }).ToList(); 
           return Json(questions, JsonRequestBehavior.AllowGet);       
        }    
    
       //Insert Question      
       public Question AddQuestion(Question question)       
       { 
          DBcontext.Questions.Add(question);  
          DBcontext.SaveChanges();  

           Question newQuestion = new Question(); 
           newQuestion.QuestionId = question.QuestionId; 
           newQuestion.QuestionText = question.QuestionText;  
                
          return newQuestionitem;   
        }  

        //Update Question  
       public JsonResult UpdateQuestion(Question question)  
       {  
           DBcontext.SaveChanges(); 
           return GetQuestion();  
       }  
}

Step 4

Create AngularJS script.

Call the WebAPI Action methods in AngularJS Script methods. The script code looks as below. See below calls to Web API URLs in Add and Update sections in the below code. These URLs will return JSON results in the browser.

JavaScript
// create AngularJs module 

var app = angular.module('qAdminModule', []);
app.controller('qAdminCtrl', function ($scope, $http, QuestionsService) {
   $scope.questionsData = null;
   QuestionsService.GetAllRecords().then(function (d) {
       $scope.questionsData = d.data; // Success
   }, function () {
       alert('Error..  !!!'); // Failure   
 });
   $scope.sortType = 'QuestionText';
   $scope.sortReverse = false;
   $scope.searchQuestion = '';
   $scope.searchQuestionId = null;
   $scope.Question = {
       QuestionId: null,
       QuestionText: ''
   };

   //Add Question
   $scope.save = function () {
       if ($scope.Question.QuestionText != null) {
           $http({
               method: 'POST',  
              url: '/QuestionAdmin/AddQuestion/',
               data: $scope.Question
           }).then(function successCallback(response) {
               $scope.questionsData.push(response.data);
               alert("Question Added Successfully !!!");
           }, function errorCallback(response) {
               alert("Error : " + response.data.ExceptionMessage);
           });
       }
       else {
           alert('Please enter QuestionText !!');
       }
   };

   // Update Question
   $scope.update = function (data) {
       if (data.QuestionId != null) {
           $scope.Question.QuestionId = data.QuestionId;  
    $scope.Question.QuestionText = data.QuestionText;       
           $http({
               method: 'POST',
               url:'/QuestionAdmin/UpdateQuestion/',
               data: $scope.Question
           }).then(function successCallback(response) {
               $scope.questionsData = response.data;
               $scope.clear();
               alert("Question Updated Successfully !!!");
           }, function errorCallback(response) {
               alert("Error in Updating: " + response.data.ExceptionMessage);
           });
       }
       else {
           alert('Error in Update !!');
       }
   };

   // Clear question details
   $scope.clear = function () {
       $scope.Question.QuestionId = null;
       $scope.Question.QuestionText = '';
   }

   // Reset question details
   $scope.reset = function () {
       $scope.searchQuestion = '';
   }

   // Edit question details
   $scope.edit = function (data) {
       $scope.Question = { QuestionId: data.QuestionId};
   }

   // Clear question details
   $scope.reset = function () {
       $scope.reset();
   }
});

// Create factory 
app.factory('QuestionsService', function ($http) {
   var fact = {};
   fact.GetAllRecords = function () {
     return $http.get('/QuestionAdmin/GetQuestion');
   }
   return fact;
});

Step 5

Create View page for UI .aspx page:

  • Create filter controls, default bind to null, if type any characters in controls, table filtered
  • Create Table which displays the result. Using ‘ng-repeat’ angular attribute shows the data in table format
  • If click header, the sorting will happen. See the code ‘filter’ attribute
ASP.NET
<asp:Content ID="Content3" runat="server">
<%-- Add angular.min.js in to project folder and specify the path --%>
<script src="../../Common/angular.min.js"></script>
<script src="../../Scripts/QuestionAdmin.js"></script>

<%--Call Angular JS module using ng-app --%>
   <div ng-app="qAdminModule" id="body">
   <div ng-controller="qAdminCtrl">

<%--Create filters UI to search the results--%>
<label for="QuestionId">QuestionId:</label></td><td>
<input type="text"  ng-model="searchQuestionId" style="width:100px">
<label for="QuestionText">Question:</label></td><td>
<input type="text"  ng-model="searchQuestion" style="width:600px">

<%-- Add Record --%>
       <a ng-click="createNew = !createNew">Create New</a>
       <table ng-show="createNew">
           <tr><td><label for="QuestionId">QuestionId</label>
           </td><td><input type="text" 
           data-ng-model="Question.QuestionId" style="width:50px" />
           </td></tr>
           <tr><td><label for="QuestionText">Question</label>
           </td><td><input type="text" 
           data-ng-model="Question.QuestionText" style="width:500px" /></td></tr>
           <tr><td><button data-ng-click="save()" 
           style="width:100px">Save</button></td>
           <td><button data-ng-click="clear()" 
           style="width:100px">Clear</button></td></tr>
       </table>
       <br />

<%-- Table to display the rows 1.Headers sortable,  2. Display records using ng-repeat --%>
     <table class="grid" style="border-collapse:collapse;">
    <th ng-click="sortType = 'QuestionId' ; 
    sortReverse = !sortReverse" > ID</th>
     <th ng-click="sortType = 'QuestionText' ; 
     sortReverse = !sortReverse" style="width:500px">Question Text</th> 
     <tr ng-repeat="items in questionsData | orderBy:sortType:sortReverse | 
     filter: { QuestionText : searchQuestion}"  style="white-space: nowrap;"  > 
              <td>{{items.EPPQuestionId}}</td>
              <td>{{items.QuestionText}}</td>
           </tr>       
   </table>
   </div></div>
</asp:Content>

Step 6

Run the website: https://localhost:80/QAdmin/QuestionAdmin.

See screen2 below to see how the screen looks like:

Image 2

Thank you for reading!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Unknown
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionCode upload Pin
pankajchhabra20-Oct-17 12:43
pankajchhabra20-Oct-17 12:43 
Questionhow to work with multiple module with angular js Pin
Mou_kol5-Oct-17 22:30
Mou_kol5-Oct-17 22:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.