【发布时间】:2015-01-13 22:32:06
【问题描述】:
我有以下代码可以获取所有帖子。它可以工作,但是当没有帖子时,它仍然将 [] 作为数据发送,因此即使数据为空也不会出现任何错误。
结果总是 ["Hello"] 作为示例,但是 []s' 没有在任何地方指定.. 不知道它们为什么在那里。
ajax 代码:
$(document).ready(function() {
$('#btnGetPosts').click(function() {
var recieverID = $('#RecieverID').val();
$.ajax({
url: "/api/Posts/GetPosts" ,
data:{username:recieverID},
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "html",
// it always skips error since it thinks that data contains [].
error: function(request, status, error) {
alert("Error, please contact the website administrator");
},
// when there is data it always shows the data like so: ["Hello"]
success: function(data) {
$("#userPosts").append(data).html();
}
});
});
});
这是我的 web-api 控制器
public List<string> GetPosts(int userID)
{
//// uses linq to get a specific user post (all posts)
var userPost = PostRepository.GetSpecificUserPosts(userID);
return userPost;
}
}
下面是我从数据库中获取所有帖子的存储库代码。
public List<string> GetSpecificUserPosts(int user)
{
using (var context = new DejtingEntities())
{
var result = context.Posts
.Where(x => x.RecieverID == user)
.Select(x => x.Body)
.ToList();
return result;
}
【问题讨论】:
标签: javascript jquery ajax asp.net-web-api