2016-06-18 42 views
3

假設我有兩個動作的方法action1action2返回對象和響應返回的區別?

措施1:

public JavaScriptSerializer action1() 
    { 
     var student = new Student() { First = "john", Last = "doe" }; 
     JavaScriptSerializer jsonStudent = new JavaScriptSerializer(); 
     jsonStudent.Serialize(student); 

     return jsonStudent; 

    } 

措施2:

public void action2() 
    { 
     var student = new Student() { First = "john", Last = "doe" }; 
     JavaScriptSerializer jsonStudent = new JavaScriptSerializer(); 
     jsonStudent.Serialize(student); 

     Response.Write(jsonStudent); 
    } 

假設我的看法有Ajax調用是這樣的:

<script> 
    $(function() { 

     $.ajax({ 
      url: 'AjaxCallsTest/action1', 
      dataType: 'json', 
      success: function (response) { 
       //code here 
      }, 
      error: function (response, status, xhr) { 
     //code here 
      } 


     }) 
    }) 
</script> 

在兩種情況下,一個寫入Response對象,另一個寫入return聲明。我的問題,即使有return,它實際上是否將jsonStudent對象添加到Response對象,如果是這樣,使用return語句寫入操作方法是毫無意義的?

感謝。

回答

1

Response.Write()實際上寫了一些東西給客戶端(aspx文檔)。它像PHP的echo一樣工作 - 它只是打印到響應中。

return另一方面,它只是向調用者函數返回一個值。所以,如果你想打印它(如action2()),你將不得不打印結果。

基本上,這裏是你將如何使用每個這樣的功能,只打印JavaScriptSerializer

措施1

JavaScriptSerializer a = action1(); 
Response.Write(a); 

措施2

action2(); 

,則回答你的問題是,如果你不需要JavaScriptSerializer對象在代碼後面,return是不必要的。但如果您稍後使用該對象,則最好將其返回並存儲。

+0

通過Response.Write()寫入Response的outputStream和打印到Response之間有什麼區別? – cptmemo

+0

老實說,我不確定,但那可能有幫助:http://www.hanselman.com/blog/ASPNETResponseWriteAndResponseOutputWriteKnowTheDifference.aspx –