【发布时间】:2017-08-16 16:15:12
【问题描述】:
我使用 WebApi2 的控制器方法
[HttpGet]
public IEnumerable<Products> GetProducts(ProductSearchCriteria searchCriteria)
{
//searchCriteria is always null here!!! Why?
return db.Instance.LoadProducts(searchCriteria);
}
我的搜索条件类
public class ProductSearchCriteria
{
private int id;
private string name;
private DateTime createdOn;
[JsonProperty]
public string Name
{
get { return this.name; }
set { this.name = value; }
}
[JsonProperty]
public DateTime CreatedOn
{
get { return this.createdOn; }
set { this.createdOn = value; }
}
[JsonProperty]
public int ID
{
get { return this.id; }
set { this.id = value; }
}
}
我在html页面中的脚本
<script>
$("#btnTest").on("click", function () {
var searchCriteria = {};
searchCriteria.ID = 0;
searchCriteria.Name = "";
//searchCriteria.CreatedOn = "";
var url = "http://localhost:8080/api/products"
$.getJSON(url, searchCriteria).done(processResponse);
});
function processResponse(response){
}
</script>
我到达了我的控制器方法(调试模式),但 ProductSearchCriteria searchCriteria 参数始终为空。如何使用 JQuery 和 WebApi2 的 get 方法发送我的 JSON 对象?
【问题讨论】:
-
GET 请求不应该有正文,因为它将被服务器忽略,因此您必须将查询字符串上的数据作为纯参数传递,并使用 [FromUri] 或更好的方法标记处理程序, 使用 POST 方法。
标签: c# jquery json asp.net-web-api getmethod