2016-06-18 43 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 –