我在构建这段代码时遇到了麻烦——我有一个 api 控制器,它通过模型从服务层获取数据,这就是我所拥有的:
api控制器
public class RoleApiController : ApiController
{
private RoleService _roleService = new RoleService();
public RoleUser GetRoleUser(int sectionID)
{
if (sectionID != null)
{
return _roleService.GetUsers(sectionID);
}
throw new HttpResponseException(HttpStatusCode.NotFound);
}
}
模型
public partial class RoleView
{
public RoleView()
{
this.Users = new HashSet<RoleUser>();
}
public ICollection<RoleUser> Users { get; set; }
}
public class RoleUser
{
public string Name { get; set; }
public string Email { get; set; }
}
错误信息:
无法将 System.Collections.Generic.IEnumberable<...RoleUser> 类型隐式转换为 RoleUser。存在显式转换(缺少演员表?)
对于这一行:return _roleService.GetUsers(sectionID);
JavaScript
<div>
Name: <span id="name"></span>
</div>
<div>
Email: <span id="email"></span>
</div>
<script type ="text/javascript" src="~/Scripts/jquery-1.9.1.min.js"></script>
<script type ="text/javascript">
getRoleUser(9, function (roleUser) {
$("#name").html(roleUser.Name);
$("#email").html(roleUser.Email);
});
function getRoleUser(id, callback) {
$.ajax({
url: "/api/RoleUser",
data: { id: id },
type: "GET",
contentType: "application/json;charset=utf-8",
statusCod: {
200: function (roleUser) { callback(roleUser); },
404: function () { alter("Not Found!"); }
}
success: function(result){
result.each(function())
}
});
}
</script>