问题
How can i SEND complex type object with array inside it using 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
});
and on asp.net mvc server:
public JsonpResult Create(Product product)
{
string thisisok = product.id;
string needthis = product.categories[0].text;
return new JsonpResult { Data = true };
}
how should i pass the complex json using the "getjson" method, i cant use ajax request because its need to be cross domain
回答1:
Well I had a similar issue; I wanted to pass an array of objects to the controller using jsonp and always I received it as null! (I mean, by GET method and with a callback feature to cross the domain)
Lets suppose I have a complex class: 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; }
}
And I want to pass an array of SearchCriteria to my Controller.
I found the solution creating an attribute:
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;
}
}
}
In the controller:
[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)});
}
In the client script when I call the method:
// 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
}
});
I hope this could help someone.
回答2:
If you need to return JSONP from your server, why are you returning JSON from your controller action? This being said the JSONP implementation of jQuery relies on adding <script>
tags to the DOM and as you know a <script>
tag sends a GET request to fetch the resource. That's a limitation of jQuery's JSONP implementation.
But firstyou need to have your server return JSONP. You could write a custom ActionResult that will return 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);
}
}
and then in your controller action return this result:
public ActionResult Create(Product product)
{
...
return new JsonpResult(new { success = true });
}
and then a client could consume this action but using a GET request (and all the limitations this has such as sending complex objects as the one you have shown):
$.getJSON('http://example.com/products/create', product, function(result) {
alert(result.success);
});
If you need to send complex objects I think that the best would be to setup a server side script on your domain that will serve as a bridge between your domain and the remote domain and then send a $.ajax
request to your script.
来源:https://stackoverflow.com/questions/11462328/how-to-send-complex-array-to-asp-net-mvc-controller-with-jsonp