我试图在 ajax 或 getjson 的帮助下从数据库中获取我的所有帖子来显示,但无法让它工作。使用 mvc web api,我有一个想要显示它的 View 。有一种称为 post 的方法,所以我的路由等没有任何问题。
我的 View js 脚本的代码,我想在名为 #userMessage 的 div 中借助我的 mvc api Controller 和 ajax 显示所有帖子。
$(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);
}
});
});
});
我的 Controller 方法来获取所有帖子
// 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;
}
最佳答案
试试这个
$(document).ready(function() {
$('#btnGetPosts').click(function() {
jQuery.support.cors = true;
var recieverID = $('#RecieverID').val();
$.ajax({
url: "/api/Posts/Posts" ,
data: {
username: recieverID
},
type: "GET",
dataType: "jsonp",
error: function(request, status, error) {
alert(request.responseText);
},
success: function(data) {
alert(data);
}
});
});
});
并在后面的代码中,
public IEnumerable<Post> GetPosts(string username)
{
// Converts Username querystring to a user-id
int id = UserRepository.GetUserId(username);
// uses linq to get a specific user post (all posts)
var userPost = PostRepository.GetSpecificUserPosts(id);
return userPost;
}
关于javascript - MVC Web Api 使用 Ajax 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27921256/