Merge pull request #757 from mlintner/master
[mono.git] / mcs / class / System.Web.Mvc3 / Mvc / JsonResult.cs
1 namespace System.Web.Mvc {
2     using System;
3     using System.Text;
4     using System.Web;
5     using System.Web.Mvc.Resources;
6     using System.Web.Script.Serialization;
7
8     public class JsonResult : ActionResult {
9
10         public JsonResult() {
11             JsonRequestBehavior = JsonRequestBehavior.DenyGet;
12         }
13
14         public Encoding ContentEncoding {
15             get;
16             set;
17         }
18
19         public string ContentType {
20             get;
21             set;
22         }
23
24         public object Data {
25             get;
26             set;
27         }
28
29         public JsonRequestBehavior JsonRequestBehavior {
30             get;
31             set;
32         }
33
34         public override void ExecuteResult(ControllerContext context) {
35             if (context == null) {
36                 throw new ArgumentNullException("context");
37             }
38             if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
39                 String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) {
40                 throw new InvalidOperationException(MvcResources.JsonRequest_GetNotAllowed);
41             }
42
43             HttpResponseBase response = context.HttpContext.Response;
44
45             if (!String.IsNullOrEmpty(ContentType)) {
46                 response.ContentType = ContentType;
47             }
48             else {
49                 response.ContentType = "application/json";
50             }
51             if (ContentEncoding != null) {
52                 response.ContentEncoding = ContentEncoding;
53             }
54             if (Data != null) {
55                 JavaScriptSerializer serializer = new JavaScriptSerializer();
56                 response.Write(serializer.Serialize(Data));
57             }
58         }
59     }
60 }