C# 返回对象和响应返回之间的区别是什么?

C# 返回对象和响应返回之间的区别是什么?,c#,jquery,asp.net-mvc,asp.net-mvc-4,asp.net-mvc-5,C#,Jquery,Asp.net Mvc,Asp.net Mvc 4,Asp.net Mvc 5,假设我有两种操作方法action1和action2: 行动1: public JavaScriptSerializer action1() { var student = new Student() { First = "john", Last = "doe" }; JavaScriptSerializer jsonStudent = new JavaScriptSerializer(); jsonStudent.Serializ

假设我有两种操作方法
action1
action2

行动1:

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

        return jsonStudent;

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

        Response.Write(jsonStudent);
    }
行动2:

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

        return jsonStudent;

    }
   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>

$(函数(){
$.ajax({
url:'AjaxCallsTest/action1',
数据类型:“json”,
成功:功能(响应){
//代码在这里
},
错误:函数(响应、状态、xhr){
//代码在这里
}
})
})
在这两种情况下,一个被写入
Response
对象,另一个有
return
语句。我的问题是,即使存在
return
,它是否真的会将
jsonStudent
对象添加到
Response
对象中,如果这样,使用
return
语句编写操作方法是没有意义的

谢谢。

Response.Write()
实际上向客户端(aspx文档)写入了一些内容。它的工作原理与PHP的
echo
-它只是打印到响应中。

另一方面,
return
,只向调用者函数返回一个值。因此,如果要打印它(如
action2()
),则必须打印结果

基本上,下面是如何使用这些函数来打印
JavaScriptSerializer

行动1

JavaScriptSerializer a = action1();
Response.Write(a);
行动2

action2();

因此,您的问题的答案是,如果您以后不需要代码中的
JavaScriptSerializer
对象,那么
return
是不必要的。但是如果以后要使用该对象,最好将其返回并存储。

写入响应的outputStream与通过Response.Write()打印响应有什么区别?老实说,我不确定,但这可能会有所帮助: