juristr
12/19/2012 - 6:51 AM

A simple JsonpResult object for being used in ASP.net MVC applications

A simple JsonpResult object for being used in ASP.net MVC applications

using System.Web.Mvc; 

public class JsonpResult : JsonResult 
{ 
  
  public string Callback { get; set; } 

  public JsonpResult() 
  { 
    JsonRequestBehavior = JsonRequestBehavior.AllowGet; 
  } 

  public override void ExecuteResult(ControllerContext context) 
  { 
    var httpContext = context.HttpContext; var callback = Callback; 
    if(string.IsNullOrWhiteSpace(callback)) callback = httpContext.Request["callback"]; 
    
    httpContext.Response.Write(callback + "("); base.ExecuteResult(context); httpContext.Response.Write(");"); 
  } 
}

Usage

Simply wrap the object to be returned, like

public JsonResult SomeControllerActionMethod()
{
  ...
  return JsonpResult(dataObject);
}

The code has been taken from the book "Programming ASP.net MVC4"