0

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 を渡す方法

4

2 に答える 2

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 の配列を 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
           }
});                 

これが誰かを助けることができることを願っています。

于 2012-10-17T17:59:02.760 に答える
0

サーバーから JSONP を返す必要がある場合、コントローラー アクションから JSONP を返すのはなぜですか? これは、jQuery の JSONP 実装は DOM へのタグの追加に依存していると言われて<script>います。ご存知のように、<script>タグはリソースを取得するために 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スクリプトにリクエストを送信するのが最善だと思います。

于 2012-07-13T06:04:00.877 に答える