如何使用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请求,因为它需要跨域

我有类似的问题; 我想用jsonp将一个对象数组传递给控制器​​,总是把它作为null接收! (我的意思是,通过GET方法并使用回调function跨域)

让我们假设我有一个复杂的类: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数组传递给我的Controller。

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

 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 } }); 

我希望这可以帮助别人。

如果您需要从服务器返回JSONP,为什么要从控制器操作返回JSON? 这就是说jQuery的JSONP实现依赖于将标记添加到DOM中,并且您知道标记发送GET请求以获取资源。 这是jQuery的JSONP实现的限制。

但是第一次需要让你的服务器返回JSONP。 您可以编写一个将返回JSONP的自定义ActionResult:

 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请求。