好吧,我有一个类似的问题;我想使用 jsonp 将一组对象传递给控制器,但我总是将它作为空值接收!(我的意思是,通过 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
}
});
我希望这可以帮助某人。