【发布时间】:2014-09-22 07:12:13
【问题描述】:
我有一个 Webapi 控制器,如下所示。 虽然很粗糙。
public async Task<HttpResponseMessage> Put(string id, [FromBody]Students studentToupdate)
{
if (!ModelState.IsValid)
{
return Request.CreateResponse(HttpStatusCode.BadRequest, "Model state Not valid");
}
if (studentToupdate == null)
return new HttpResponseMessage(HttpStatusCode.BadRequest);
Students student = await Context.Set<Students>().FindAsync(new Guid(id));
student.FirstName = studentToupdate.FirstName;
student.LastName = studentToupdate.LastName;
student.Address = studentToupdate.Address;
student.DOB = studentToupdate.DOB;
student.Phone = studentToupdate.Phone;
Context.Entry(student).State = EntityState.Modified;
try
{
int result = await Context.SaveChangesAsync();
return result > 0 ? Request.CreateResponse<Students>(HttpStatusCode.OK, student) : Request.CreateResponse(HttpStatusCode.InternalServerError);
}
catch (Exception ex)
{
return Request.CreateResponse<Exception>(ex);
}
}
我的角度控制器是这样的。它在 coffeescript 中。
SiteAngular.Student.controller 'Edit',['$scope','$state','$stateParams','Factory',($scope,$state,$stateParams,factory)->
id=$stateParams.id
student = factory.get id:id
$scope.student=student
$scope.Update = (id,student)->
factory.update
id:id
studentToupdate:student
]
最后一点,我的 html 很可能是一个列表,它的按钮有一个更新方法:
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" value="Save" class="btn btn-default" ng-click="Update(student.StudentGuid,student)"/>
</div>
</div>
在 div 上方,我有 ng-repeat 循环到表中以获取 student 的各种属性。在更新方法中,我想将 Guid 和 student 对象发送到提到的 webapi 控制器
问题在于 webapi 控制器 string id 完美接收了 guid。但是 studentToUpdate 的所有属性都是 null 。我检查了标题,它完全像
Accept application/json, text/plain, */*
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Content-Length 250
Content-Type application/json;charset=utf-8
Cookie __RequestVerificationToken=SBC0HZDwZOEyOfG0dMN0Da-MqFYQoVoiaG3_LIpnXc5a4tSsu1wP4U8Qy3cgrw7w_rMmDu5577pVrZ0Kmzo9YCZcLvFY93f37Heat160h6k1
Host localhost:3090
Referer http://localhost:3090/
User-Agent Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0
谁能告诉我为什么 id 被填充而不是 FromBody 学生对象。 webapi put方法中student对象的属性全部为null??
使用 webapi v5.1.0.0。有什么线索吗?
【问题讨论】:
标签: angularjs asp.net-web-api asp.net-web-api2 ngresource