Assume I have two actions methods action1 and action2:
Action1:
public JavaScriptSerializer action1()
{
var student = new Student() { First = "john", Last = "doe" };
JavaScriptSerializer jsonStudent = new JavaScriptSerializer();
jsonStudent.Serialize(student);
return jsonStudent;
}
Action2:
public void action2()
{
var student = new Student() { First = "john", Last = "doe" };
JavaScriptSerializer jsonStudent = new JavaScriptSerializer();
jsonStudent.Serialize(student);
Response.Write(jsonStudent);
}
Assume my view has a Ajax call like this:
<script>
$(function () {
$.ajax({
url: 'AjaxCallsTest/action1',
dataType: 'json',
success: function (response) {
//code here
},
error: function (response, status, xhr) {
//code here
}
})
})
</script>
In the two cases one was written to Response object and the other has a return statement. my question even when there is a return, does it actually adds the jsonStudent object to the Response object if so writing action methods with return statements are meaningless?
Thanks.
Response.Write() actually writes something to the client (the aspx document). It works like PHP's echo - it just prints to the response.
return, on the other hand, just returns a value to the caller function. So, if you want it to be printed (like action2()), you would have to print the result.
Basically, here is how you would use each of those functions to just print the JavaScriptSerializer:
Action1
JavaScriptSerializer a = action1();
Response.Write(a);
Action2
action2();
So, the answer to your question is, that if you don't need the JavaScriptSerializer object in the code later, the return is unecessary. But if you will use that object later, you better return it and store it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With