我试图从数据库中获取所有帖子,并在ajax或getjson的帮助下显示,但无法使其正常工作。使用mvc web api,我有一个视图,我想要显示它。有一种方法工作称为邮政,所以没有错我的路由等MVC Web Api通过Ajax获取数据
代码为我的意见js脚本,我想显示所有职位的帮助我的mvc api控制器和ajax在一个名为#userMessage的div。
$(document).ready(function() {
$('#btnGetPosts').click(function() {
jQuery.support.cors = true;
var recieverID = $('#RecieverID').val();
$.ajax({
url: "/api/Posts/GetPosts" ,
//data: (?)
type: "GET",
dataType: "jsonp",
error: function(request, status, error) {
alert(request.responseText);
},
success: function(data) {
alert(data);
}
});
});
});
我控制器的方法来获取所有帖子
// GET: api/Posts
public IEnumerable<Post> GetPosts()
{
//querystring is made to get the recieverID, it's also reachable in the view. //("#RecieverID")
string querystring = HttpContext.Current.Request.QueryString["Username"];
// Converts Username querystring to a user-id
int id = UserRepository.GetUserId(querystring);
// uses linq to get a specific user post (all posts)
var userPost = PostRepository.GetSpecificUserPosts(id);
return userPost;
}
我PostRepository.GetSpecifiedUserPosts方法在我的仓库
public List<Post> GetSpecificUserPosts(int user)
{
using (var context = new DejtingEntities())
{
var result = context.Posts
.Where(x => x.RecieverID == user)
.OrderByDescending(x => x.Date)
.ToList();
return result;
}
会发生什么?您的'.ajax''错误'处理程序是否被调用?如果是这样,服务器的'statusCode'是什么,'responseText'(如果有的话)是什么?此外,它看起来像你使用的是WebAPI,而不是MVC(它们是不同的)。如果你正在使用'ApiController',你应该在你的问题中删除你的MVC标签及其提及。 – danludwig