我正在尝试使用ASP.net MVC和angular.js创建单页面应用程序。我按照Here的指示行事。我的模型类如下
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
我的app.js类如下
//Step-01 : Define Module
var PersonModule = angular.module('PersonModule', ['ngRoute', 'ngResource']);
//Step:04 : Define Module Configuration
PersonModule.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', {
controller: DetailsController,
templateUrl: 'list.html'
})
.when('/new', {
controller: CreateController,
templateUrl: 'new.html'
})
.otherwise({ retdirectTo: '/' });
}]);
//Step : 02 Define Factory for Hold resource and request server
PersonModule.factory('PersonResource', function ($resource) {
return $resource('/api/Person/:id', { id: '@id' }, { update: { method: 'PUT', isArrary: true } });
});
//Step : 03 Define Controller i.e. business logic
var CreateController = function ($scope, $location, PersonResource) {
//Create a variable in the controller for save button catpion
$scope.Action = 'Create';
//Define method for Create
$scope.Create = function () {
//Call the Save method of $resource and passed paremeter to it $scope.Person here Person is a model
PersonResource.save({ post: $scope.Person }, function () {
//If call is success then call path method of $location directive for redirect
$location.path('#/');
});
}
}
var DetailsController = function ($scope, PersonResource) {
//Call the query method of $resource directive
$scope.Persons = PersonResource.query();
}
我的html文件代码如下
<h2>{{Action}} Person</h2>
<form>
<div>
<label for="Person.Name">Person:</label>
<input ng-model="Person.Name" name="Name" />
</div>
<div>
<label for="Person.Address">Address:</label>
<input ng-model="Person.Address" name="Address" />
</div>
<div>
<a href="#/">Cancel</a>
<button ng-click="Create()">{{Action}}</button>
</div>
</form>
下面给出了我的服务器端控制器Put方法: 这是我的服务器控制器操作方法,它放置数据:
public HttpResponseMessage Post(Person person)
{
context.Persons.Add(person);
context.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, person);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = person.Id }));
return response;
}
当我按下保存按钮时,它获取名称和地址的空值,虽然Id是一个标识字段,但它获取Id的值,最后保存到名称和地址为空值的数据库。
当我从Chrome的“网络”标签中查看开发者资源时,它会显示以下信息:
答案 0 :(得分:1)
从客户端发送的json结构应该映射到.net类的结构,以便绑定才能正常工作。
尝试发送帖子\ put as
PersonResource.save($scope.Person, function (){
此外,您的Person json对象应具有id
属性,该属性将用于构造资源URL。
如果响应是数组,PUT资源声明也应该只声明isArray=true
。