2011-09-13 65 views
0

我有一個問題,同時從檢索的Json傳來的數據...問題而receving JSON結果.. Asp.net MVC 3

我傳遞一些值到$阿賈克斯,我想處理該在控制器值..

請幫幫忙,我怎麼可以檢索控制器值...

jQuery代碼

var userID = @Model.User.UserID; 
     var postID = @Model.Post.PostID; 
     var commentBody = $('#textareaForComment').val(); 

$('#btnSubmit').click(function (e) 
    { 

     e.preventDefault(); 
     var postdata = 
     { 
      CommentBody: commentBody, 
      PostID: postID, 
      UserID: userID    
     }; 

     $.ajax({ 
      url: '@Url.Action("SubmittedComment","Post")', 
      data: postdata, 
      success: function(data) { 
       $('#showComments').html(data); 
      } 
     }); 
    }); 

現在我打電話中寶SubmittedComment行動st控制器,我想要在該行動中有PostID,USerID和CommentBody,並且希望將其存儲在diff變量中。

請大家幫忙。 THX

控制器代碼

public JsonResult SubmittedComment(string CommentBody,UserID,PostID) 
     { 

      var result = CommentBody // i am not able to get the value here .... 

     } 

回答

2
$('#btnSubmit').click(function() { 
    $.ajax({ 
     url: '@Url.Action("SubmittedComment","Post")', 
     // Values should be evaluated at the callback, not at page load time 
     // this is not the case for UserID and PostID, but for CommentBody it is 
     data: { 
      UserID: @Model.User.UserID, 
      PostID: @Model.Post.PostID, 
      CommentBody: $('#textareaForComment').val() 
     }, 
     success: function(data) { 
      // Controller action returns data in Json format, so .html() makes no sence here. 
      // Change action to return html markup via PartialView or change this function to 
      // parse Json. Also, returning Json via GET request is forbidden by default by ASP.NET MVC (just in case you don't know 
      $('#showComments').html(data); 
     } 
    }); 
    return false; // Equals to e.preventDefault() 
}); 
+1

+1指出CommentBody應該在點擊處理程序中進行評估。 – RoccoC5

+0

嚴重... dint知道...非常有幫助.... –

1

你的jQuery AJAX調用不執行HTTP POST

編輯:請注意,您也應該在按鈕點擊事件中評估$('#textareaForComment').val(),正如Artem指出的那樣。

選項type: 'POST'添加到您的來電:

$('#btnSubmit').click(function (e) 
{ 
    e.preventDefault(); 
    var postdata = 
    { 
     CommentBody: $('#textareaForComment').val(), 
     PostID: postID, 
     UserID: userID    
    }; 

    $.ajax({ 
     url: '@Url.Action("SubmittedComment","Post")', 
     data: postdata, 
     type: 'POST', 
     success: function(data) { 
      $('#showComments').html(data); 
     } 
    }); 
}); 

另外,使用post()功能:

$.post('@Url.Action("SubmittedComment","Post")', 
    postdata, 
    success: function(data) { 
     $('#showComments').html(data); 
    } 
); 

你也想給[HttpPost]屬性添加到您的控制器動作,限制exucution該方法僅適用於HTTP POST:

[HttpPost] 
public JsonResult SubmittedComment(string CommentBody, int UserID, int PostID) 
{ 
    // ... snip ... 
} 
+0

明白了......我完全忘了把類型放在$ .ajax調用中...... thx指出它...... –