使用 WebAPI 更新数据库的 MVC、AngularJs 示例





5.00/5 (3投票s)
使用 Angular 和 Web API 更新和插入数据库的示例
引言
本文档解释了如何使用 Angular JS、Web API 和实体框架在 MVC 中简单地更新和插入数据库表。
背景
有很多文章无法解释如何使用 MVC、AngularJS 和 Web API 的技术组合来更新数据库。我创建了一个示例项目来解释使用 AngularJS 和 Web API 是多么简单。
Using the Code
步骤 1
在 Visual Studio 中创建一个 MVC 网站。
第二步
创建一个名为“Question
”的数据库表,包含字段 QuestionId
和 QuestionText
。
使用数据库上下文名称为 DBcontext
创建实体框架 .edmx 文件。将 Question 表添加到项目中。在将 EF 类生成到项目中后,Question
模型类如下所示
public partial class Question
{
public int QuestionId { get; set; }
public string QuestionText { get; set; }
}
步骤 3
如屏幕 1 所示,将 Web API Controller 添加到项目中
- 创建 Action 方法,
GetQuestion()
、AddQuestion()
、UpdateQuestion()
数据库,这些 Action 返回JsonResult
。 QuestionAdmin()
调用View
。此 Action 启动 UI。
Controller 类代码如下所示
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();
}
}
步骤 4
创建 AngularJS 脚本。
在 AngularJS 脚本方法中调用 WebAPI Action 方法。脚本代码如下所示。请参阅以下代码中的“添加”和“更新”部分对 Web API URL 的调用。这些 URL 将在浏览器中返回 JSON 结果。
// 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;
});
步骤 5
创建 UI .aspx 页面
- 创建筛选控件,默认绑定到
null
,如果在控件中键入任何字符,则表将被筛选 - 创建显示结果的表。使用“
ng-repeat
”angular 属性以表格形式显示数据 - 如果单击标题,将发生排序。请参阅代码中的“
filter
”属性
<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>
步骤 6
运行网站:https://:80/QAdmin/QuestionAdmin。
请参阅下面的屏幕 2,了解屏幕的外观
感谢阅读!