如何将复杂对象传递给ASP.NET的WebAPI从jQuery的AJAX调用get? [英] How to pass complex object to ASP.NET WebApi GET from jQuery ajax call?

查看:199
本文介绍了如何将复杂对象传递给ASP.NET的WebAPI从jQuery的AJAX调用get?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JavaScript中的下列复杂的对象,其中包含过滤器选项

I have the following complex object in JavaScript which contains filter options

var filter={caseIdentifiter:'GFT1',userID:'2'};



我要传递给ASP.NET MVC4的WebAPI控制器GET

which I want to pass to an ASP.NET MVC4 WebApi controller GET

[HttpGet]
public IEnumerable<JHS.Repository.ViewModels.CaseList> Get([FromBody]Repository.InputModels.CaseListFilter filter)
{
  try
  {
    return Case.List(filter);
  }
  catch (Exception exc)
  {
    //Handle exception here...
    return null;
  }
}



使用jQuery的AJAX调用

using an jQuery ajax call

var request = $.ajax({
  url: http://mydomain.com/case,
  type: 'GET',
  data: JSON.stringify(filter),
  contentType: 'application/json; charset=utf-8',
  cache: false,
  dataType: 'json'
});

在ASP.NET控制器方法过滤器的对象是空。如果我将其更改为POST过滤对象正确地传递。有没有一种方法,以一个复杂的对象传递给GET?

The "filter" object in the ASP.NET controller method is "null". If I change it to a POST the filter object is passed correctly. Is there a way to pass a complex object to a GET?

我不想参数分离出的URL一样会有许多人这会使其效率低下,这将是很难有可选的参数,这种方式方法的签名保持,即使添加了新的参数不变。

I do not want to separate out the parameters to the URL as there will be a number of them which would make it inefficient, it would be hard to have optional parameters, and this way the method signature stays constant even if new parameters are added.

推荐答案

找到这个计算器问题/答案后

After finding this StackOverflow question/answer

复杂类型越来越空了ApiController参数

在控制器方法[FromBody]属性需要是[FromUri]因为一个GET不具有体。经过这一变化的过滤器复杂的对象是否正确过去了。

the [FromBody] attribute on the controller method needs to be [FromUri] since a GET does not have a body. After this change the "filter" complex object is passed correctly.

这篇关于如何将复杂对象传递给ASP.NET的WebAPI从jQuery的AJAX调用get?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆