2012-07-12 111 views
0

我怎样才能使用JSONP如何发送复杂的阵列,以ASP.NET MVC控制器JSONP

var product= {categories:[ {id:1,text:"cat 1"},{id:2,text:"cat 2"}],id:43,price:3535}; 
$.getJSON(url ,product, function (data) { 

//i can get the data from the server but i cant pass the complex array to the server 
}); 

和asp.net MVC服务器发送信息内配置阵列复杂类型的对象:

public JsonpResult Create(Product product) 
    { 
     string thisisok = product.id; 
     string needthis = product.categories[0].text;   
     return new JsonpResult { Data = true }; 
    } 

我应该如何通过使用“的getJSON”方法的复杂JSON, 我不能使用AJAX请求,因为其需要被跨域

+0

执行跨域AJAX调用的最佳方式是使用代理。 – ahren 2012-07-12 23:55:34

回答

0

如果哟你需要从你的服务器返回JSONP,你为什么从你的控制器动作返回JSON?这就是说jQuery的JSONP实现依赖于向DOM添加<script>标签,并且您知道<script>标签发送GET请求来获取资源。这是jQuery的JSONP实现的限制。

但首先你需要让你的服务器返回JSONP。你可以写一个自定义的ActionResult,将返回JSONP:

public class JsonpResult : ActionResult 
{ 
    private readonly object _obj; 

    public JsonpResult(object obj) 
    { 
     _obj = obj; 
    } 

    public override void ExecuteResult(ControllerContext context) 
    { 
     var serializer = new JavaScriptSerializer(); 
     var callbackname = context.HttpContext.Request["callback"]; 
     var jsonp = string.Format("{0}({1})", callbackname, serializer.Serialize(_obj)); 
     var response = context.HttpContext.Response; 
     response.ContentType = "application/json"; 
     response.Write(jsonp); 
    } 
} 

,然后在你的控制器行动回报这样的结果:

public ActionResult Create(Product product) 
{ 
    ... 
    return new JsonpResult(new { success = true }); 
} 

,然后客户端会消耗此操作,但使用GET请求(和这一切都有局限性,如发送复杂的对象,你已经中所示):

$.getJSON('http://example.com/products/create', product, function(result) { 
    alert(result.success); 
}); 

如果需要发送复杂的对象我认为最好是设置服务器端脚本将在您的域名和域名之间起桥梁作用,然后向您的脚本发送$.ajax请求。

+0

问题不在于从服务器获取jsonp – Yojik 2012-07-13 12:33:15

+0

那么,这绝对是您向我们显示的代码的问题。如果你说这不是问题,那么为什么你的控制器操作返回Json? JSON与JSONP不同。但正如我所说,JSONP的jQuery实现仅适用于GET请求,所以即使您设法从您的控制器操作中返回适当的JSONP(如我的答案中所示),您可能会受到此限制。您可以使用服务器端代理。 – 2012-07-13 12:35:34

3

那么我有一个类似的问题;我想使用jsonp将一个对象数组传递给控制器​​,并且始终将其作为null接收! (我的意思是,通过GET方法,用回拨功能交叉域)

让我们假设我有一个复杂的类:SearchCriteria

public class SearchCriteria 
{ 
    public string destination {get; set;} 
    public string destinationTitle { get; set; }   
    public string departure { get; set; } 
    public string month { get; set; } 
    public string nights { get; set; } 
    public string cruiseline { get; set; } 
} 

我想SearchCriteria数组传递给我的控制器。

我找到了解决方案创建一个属性:

public class JsonpFilter : ActionFilterAttribute 
{ 
    public string Param { get; set; } 
    public Type JsonDataType { get; set; } 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     if (filterContext.HttpContext.Request.ContentType.Contains("application/json")) 
     { 
      string inputContent = filterContext.HttpContext.Request.Params[Param];     
      JavaScriptSerializer serializer = new JavaScriptSerializer(); 
      var result = serializer.Deserialize(inputContent, JsonDataType); 
      filterContext.ActionParameters[Param] = result; 
     } 
    } 
} 

在控制器:

[JsonpFilter(Param = "criterias", JsonDataType = typeof(SearchCriteria[]))] 
public JsonpResult getResultSet(SearchCriteria[] criterias) 
{    
    foreach (SearchCriteria sc in criterias) 
    { 
     // TODO (normalize criteria, etc..) 
    } 
    return Jsonp(new { content = RenderPartialViewToString("getResults", criterias)}); 
} 

在客户端脚本时,我调用的方法:

// Populate the Array of objects 

var criteria = new Array(); 
for (var i = 0; i < 4; i++) { 
    criteria.push({ "destination": $("#DestinationValue" + i).val(), 
        "departure": $("#PortValue" + i).val(), 
        "month": $("#Month" + i).val(), 
        "nights": $("#Nights" + i).val(), 
        "cruiseline": $("#CruiselineValue" + i).val()});     
} 

// Call the controller; note i do not specify POST method and I specify "callback" in order to enable jsonp that cross the domain. 

$.ajax({ 
    url: "getResultSet?callback=?", 
    dataType: 'json', 
    data: {"criterias" : JSON.stringify(criteria)}, 
    contentType: 'application/json; charset=utf-8', 
    success: function (data) { 
       // call return from the controller 
      } 
});     

我希望这可以帮助某人。

+0

感谢您 - 几乎排除了我,除了'filterContext.HttpContext.Request.ContentType'总是'“”' - 任何想法?使用与您完全相同的ajax调用(除了不同的数据) – rwalter 2013-03-06 11:23:47

相关问题