通过Json传递IEnumerable

时间:2013-04-09 16:15:18

标签: asp.net-mvc jquery ienumerable

我在一个简单的评论数据库MVC程序中创建了一个“赞”按钮。 当我将鼠标悬停在“赞”按钮上时,我将注释的ID传递给HomeController中的ActionResult。问题(我认为)是我不知道如何将IEnumerable Likes列表传递给ajax。

脚本和HTML部分:

HTML:

<a href="#" class="likes" title="No likes yet." id="@comment.ID">Like this</a>

脚本:

$(".likes").hover(function (event) {

    var Liker = { "CID": event.target.id };

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/Home/ShowLike/",
        data: JSON.stringify(Liker),
        dataType: "json",
        success: function (data) {
            $.each(data.Name, function (value) {
                alert(value);
            });
        },
        error: function (xhr, err) {
            // Note: just for debugging purposes!
            alert("readyState: " + xhr.readyState +
            "\nstatus: " + xhr.status);
            alert("responseText: " + xhr.responseText);
        }
    });

});

HomeController - &gt; ShowLike

    [HttpPost]
    public ActionResult ShowLike(Liker ids)
    {
        LikesRepository lkrep = new LikesRepository();

        IEnumerable<Like> list = lkrep.GetLikes(ids.CID);

        return Json(list);
    }

LikesRepository

 public class LikesRepository
 {
    CommentDBDataContext m_db = new CommentDBDataContext();

    public IEnumerable<Like> GetLikes(int iden)
    {
        var result = from c in m_db.Likes
                     where c.CID == iden
                     orderby c.Name ascending
                     select c;

        return result;
    }

    public void AddLike(Like c)
    {
        m_db.Likes.InsertOnSubmit(c);
        m_db.SubmitChanges(); //This works
    }
}

1 个答案:

答案 0 :(得分:0)

在深入研究问题之后,我们发现它实际上是在触发内部服务器错误(500)。这是由将LINQ序列化为SQL对象到JSON的循环引用引起的。这个问题已多次讨论......

How to remove circular reference in Entity Framework?

How did I solve the Json serializing circular reference error?

Circular Reference exception with JSON Serialisation with MVC3 and EF4 CTP5w

另一种解决方案是将数据作为字符串列表返回,因为它们只需要名称。