【发布时间】:2015-03-11 08:33:33
【问题描述】:
我正在尝试在 ajax 或 getjson 的帮助下从数据库中获取我的所有帖子,但无法使其正常工作。使用 mvc web api,我有一个要显示它的视图。有一种名为 post 的方法,所以我的路由等没有问题。
我的视图 js-script 的代码,我想在我的 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;
}
【问题讨论】:
-
会发生什么?你的
$.ajaxerror处理程序被调用了吗?如果是这样,来自服务器的statusCode是什么,responseText是什么(如果有)?此外,看起来您使用的是 WebAPI,而不是 MVC(它们是不同的)。如果您使用的是ApiController,则应删除您的 MVC 标签及其在问题中的提及。
标签: javascript jquery ajax asp.net-mvc asp.net-web-api