2012-07-12 75 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

相關問題