【发布时间】:2013-04-09 16:15:18
【问题描述】:
我正在一个简单的评论数据库 MVC 程序中创建一个“Like”按钮。 当我将鼠标悬停在“Like”按钮上时,我将评论的 ID 传递给 HomeController 中的 ActionResult。问题(我认为)是我不知道如何将喜欢的 IEnumerable 列表传递给 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 -> ShowLike
[HttpPost]
public ActionResult ShowLike(Liker ids)
{
LikesRepository lkrep = new LikesRepository();
IEnumerable<Like> list = lkrep.GetLikes(ids.CID);
return Json(list);
}
喜欢存储库
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
}
}
【问题讨论】:
-
返回 IEnumerable 的其他一切看起来都很好。您应该使用 JS 调试器来查看 ajax 成功函数中的 data 属性,它将让您了解如何在返回时处理数据(假设您的数据不为空)。我喜欢使用 chrome 并在我的成功函数中设置断点,然后将鼠标悬停在数据对象上。
标签: asp.net-mvc jquery ienumerable