2
因此,我正在嘗試爲博客創建評論部分。我無法識別在我的jQuery中打開的博客文章ID。Ajax調用在ASP中無法正常工作MVC
我從Chrome控制檯
GET http://localhost:46223/api/posts//comments
的帖子ID應該是插圖中的雙斜槓,但它沒有得到這些錯誤。當我手動輸入ajax調用中的postID時,它可以很好地工作。
一個Api控制器暴露數據庫中的註釋,下面的相關代碼。
[Route("api/posts/{postId:long}/comments")]
public class CommentsController : Controller
{
readonly BlogDataContext _dbContext;
public CommentsController(BlogDataContext db)
{
_dbContext = db;
}
// GET: api/values
[HttpGet]
public IQueryable<Comment> Get(long postId)
{
return _dbContext.Comments.Where(x => x.PostId == postId);
}
當我按下「顯示評論」鏈接了鍍鉻的控制檯給我我早先提到的錯誤。下面我的部分視圖的相關代碼。下面最重要的一行只是第一行。
<a href="#" class="show-comments">Show Comments</a>
<div class="comments-container hide">
<h3>Comments</h3>
<div class="comments">
</div>
<hr />
<div>
<a href="#" class="add-comment">Add a comment</a>
<div class="new-comment hide">
<form role="form">
<div class="form-group">
<textarea name="Body" class="new-comment form-control" placeholder="Enter comment here..."></textarea>
<button type="submit" class="btn btn-default">Create Comment</button>
</div>
</form>
</div>
</div>
</div>
相關的代碼片斷從我的.js
$(document).on('click', '.show-comments', function (evt) {
evt.stopPropagation();
new Post(this).showComments();
return false;
});
function Post(el) {
var $el = $(el),
postEl = $el.hasClass('blog-post') ? $el : $el.parents('.blog-post'),
postId = postEl.data('post-id'),
addCommentEl = postEl.find('.add-comment'),
newCommentEl = postEl.find('.new-comment'),
commentEl = newCommentEl.find('[name=Body]'),
commentsContainer = postEl.find('.comments-container'),
commentsEl = postEl.find('.comments'),
showCommentsButton = postEl.find('.show-comments'),
noCommentsEl = postEl.find('.no-comments');
return {
addComment: addComment,
renderComment: renderComments,
showAddComment: showAddComment,
showComments: showComments,
};
function showComments() {
PostCommentService.getComments(postId).then(renderComments);
}
var PostCommentService = (
function PostCommentService() {
function call(postId, method, data) {
return $.ajax({
// RESTful Web API URL: /api/posts/{postId}/comments
url: ['/api/posts', postId, 'comments'].join('/'), // If I Change the 'postId' here to an integer of an existing postId, it works perfectly.
type: method,
data: JSON.stringify(data),
contentType: 'application/json'
});
}
return {
// Add comment by calling URL with POST method and passing data
addComment: function (comment) {
return call(comment.PostId, 'POST', comment);
},
// Get comments by calling URL with GET method
getComments: function (postId) {
return call(postId, 'GET');
}
};
})();
對不起,如果我錯過了,包括什麼,但我有很多的代碼。如果您需要了解其他信息,請告訴我。
我也很感激只是爲了一些建議,我的錯誤可能是。
謝謝!我的評論部分是在一個博客博客課,所以我剛剛添加了data-post-id屬性,並且它工作正常!非常感謝 – user3621898