我有一个简单的html表单,包含2个文本框和一个按钮,如下所示:
<div class="container" ng-controller="GetStudentController">
<div class="form-group" style="padding-bottom:40px;">
<h2 style="text-align:center;">Index</h2>
<input id="Text1" class="form-group form-control" ng-model="ime" type="text" />
<input id="Text1" class="form-group form-control" ng-model="prezime" type="text" />
<input type="button" style="float:right;" class="form-group btn btn-primary" ng-click="snimi(ime,prezime)" value="Snimi" />
</div>
</div>
这是我的AngularJS代码:
var app = angular.module("myApp", []);
app.service("GetStudentsService", function ($http) {
this.getData = function ()
{
return $http({
metod: "GET",
url: "/Home/GetStudent"
}).success(function (data) {
return data;
}).error(function () {
alert("error");
return null;
});
}
this.PostData = function (data)
{
$http.post("/Home/SnimiStudenta",data)
.success(function () {
getData();
}).error(function (response) {
alert(response);
});
}
});
app.controller("GetStudentController", function ($scope, GetStudentsService) {
$scope.data = null;
GetStudentsService.getData().then(function (response) {
$scope.data = response.data;
});
$scope.snimi = function (ime, prezime) {
var data = $.param({
fName: ime,
lName: prezime
});
GetStudentsService.PostData(data);
};
});
这是负责将记录保存到数据库的操作:
[HttpPost]
public void SnimiStudenta(// I would like to pass an Student object here)
{
Student s = new Student();
s.Ime = "1";
s.Prezime = "2";
Connection.dc.Students.Add(s);
Connection.dc.SaveChanges();
}
我有几个问题:
有人可以帮我解决这个问题吗?
谢谢!
答案 0 :(得分:2)
你必须构建一个类似于你的C#类(在属性名称方面)的js对象,它用作action方法的参数,并发布js对象
$scope.snimi = function (ime, prezime) {
var data = { Ime: ime, Prezime: prezime};
GetStudentsService.PostData(data);
};
你的行动方法,
[HttpPost]
public void SnimiStudenta(Student s)
{
Connection.dc.Students.Add(s);
Connection.dc.SaveChanges();
}
答案 1 :(得分:0)
至于为何你得到一个&#34; undefined&#34;调用getData()
时出错,不是因为getData
未定义,而是因为getData
返回的承诺只包含数据,而不是整个响应。所以改变:
GetStudentsService.getData().then(function (response) {
$scope.data = response.data;
});
到:
GetStudentsService.getData().then(function (data) {
$scope.data = data;
});