学习Angularjs向数据库添加数据
今天学习angularjs向数据库添加数据。
学习此篇,得从以往几篇开始,因为那还有创建数据表等演示。
现在来创建一个添加的存储过程:
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE PROCEDURE [dbo].[usp_Goods_Insert] ( @Item NVARCHAR(55), @Description NVARCHAR(20), @Qty DECIMAL(10,2) ) AS IF EXISTS(SELECT TOP 1 1 FROM [dbo].[Goods] WHERE [Item] = @Item) BEGIN RAISERROR(N'[%s]物料已经存在.',16,1,@Item) RETURN END ELSE INSERT INTO [dbo].[Goods] ([Item],[Description],[Qty]) VALUES (@Item,@Description,@Qty) GO
在ASP.NET MVC 的控制器中,添加2个操作,一个是为网页准备,一个是添加Action:
var GoodsApp = angular.module('GoodsApp', []); GoodsApp.controller('GoodsAdditionController', function ($scope, $http) { $scope.GoodsAddition = function () { var obj = {}; obj.Item = $scope.Item; obj.Description = $scope.Description; obj.Qty = $scope.Qty; $http({ method: 'POST', url: '/Goods/Insert', dataType: 'json', headers: { 'Content-Type': 'application/json; charset=utf-8' }, data: JSON.stringify(obj), }).then( function success(response) { if (response.data.Success) { alert("数据添加成功。"); window.location.href = response.data.RedirectUrl; } else { alert(response.data.ExceptionMessage); } }, function error(error) { alert(response.error.data); }); }; });