【问题标题】:Cannot implicitly convert type - missing cast - models.views无法隐式转换类型 - 缺少演员表 - models.views
【发布时间】:2013-03-19 11:02:46
【问题描述】:

我在构建此代码时遇到问题 - 我有一个 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>

【问题讨论】:

标签: c# asp.net-mvc asp.net-web-api


【解决方案1】:

嗯,当您应该只返回一个用户时,您返回了一组用户?我无法从您显示的代码中判断您是否真的想要一个集合,但这是您的问题。

这将使您的代码编译,但可能不是您想要的解决方案:

return _roleService.GetUsers(sectionID).FirstOrDefault();

【讨论】:

  • 感谢帮助编译,但现在我意识到它没有显示任何应有的结果。至于我想返回什么 - 我想返回一个集合,所以我会在服务中更改我的代码吗?
  • 如果您希望控制器操作返回集合,您应该将 Controller 的返回类型从 RoleUser 更改为 IEnumerable 并删除我在答案中添加的 .FirstOrDefault()。
  • 感谢您的照顾 - 现在我认为 javascript 在显示信息时可能存在问题
  • 好吧,您可能编写了期望返回单个对象而不是列表的 javascript。您可能需要在 ajax 成功函数中执行 result.each(function(index, element) {});
  • 如果您可以查看并分享您的建议,我在上面添加了我的 javascript。非常感谢您的帮助。
【解决方案2】:

您的方法声明说它返回 RoleUser(单数),而您的方法会暗示它返回一个集合。因此,您要么需要修复方法以返回列表,要么只从 GetUsers 方法返回单个结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多