2009-02-23 164 views
19

我有一個網站,每個用戶的頁面顯示評論,並允許其他用戶添加評論。我想擁有它,因此添加評論表單位於頁面上,當用戶添加評論時,它會添加到數據庫中,並使用AJAX註釋部分顯示。我使用jQuery來處理AJAX和LINQ to SQL來處理數據庫邏輯。如何做到這一點,以便在評論添加到數據庫後,評論部分刷新和更新而不刷新頁面?ASP.NET MVC AJAX與jQuery

回答

22

您需要利用jQuery ajax調用激發的'success'(或'complete')事件來觸發隨後的AJAX調用,以刷新評論的內容。這可能會是這個樣子(翅它,未經測試):

function UpdateComments(){ 
    resultHTML = jQuery.ajax({ 
     type: 'GET', 
     url: 'Comments/List/UserID' 
    }).responseText; 

    $('#comments').html(resultHTML); 
} 

function PostComment(targetUserID, commenterUserID, comment) 
jQuery.ajax({ 
     type: 'POST', 
     contentType: 'application/json; charset=utf-8', 
     data: $.toJSON({review: comment, id:targetUserID, commenter:commenterUserID}), 
     dataType: 'json', 
     url: 'Comments/Add', 
     success: function(result){ 
      // Only update comments if the post was successful: 
      resultJson = $.evalJSON(result); 
      if(resultJson['success'] == true){ 
       UpdateComments();      
      } 
     } 
    }); 

編輯的JSON代碼會利用jQuery插件jQuery的JSON(http://code.google.com/p/jquery-json/

+2

的URL應該是:「/評論/添加」 ......否則,URL被附加到當前的網址,你將最有可能獲得404 – 2010-01-20 15:35:08

+1

事實上,使用其中一個MVC幫助程序來實際生成路徑可能會更好,因爲如果您的站點在IIS中的另一個網站下作爲嵌套應用程序運行,則領導/還會拋出一些東西 – Matt 2010-10-01 14:30:15

11

的迴應馬特,另一路要提交表單數據,而不是JSON,可以在jQuery.ajax函數的'data'字段中調用$('#form')。serialize()。這將消除對插件的需求。

此外,我不是這方面的專家,仍然試圖自己學習它,但是當您可以將ASP.NET MVC的響應插入到頁面中時,需要同時具有POST和GET請求?這會導致一個請求。儘管這種方法可能有一個合理的理由。我想我的應該是這樣的:

// The Controller Action should return a PartialView as response, 
    // so just a user control that contains the comments. 
function PostComment(targetUserID, commenterUserID, comment) 
jQuery.ajax({ 
    type: 'POST', 
    data: $('#commentForm').serialize(), 
    url: 'Comments/Add', 
    success: function(result){ 
     $('#comments').html(result); 


     } 
    } 
    });