ASP.NET的WebAPI - 如何传递对象,$ .getJSON [英] ASP.NET WebAPI - how to pass object with $.getJSON
问题描述
我有以下ASP.NET的WebAPI控制:
I've a ASP.NET WebAPI control below :
public SomeObject GetBenchMarkData(Comment comment)
{
//do stuff
}
在客户端我想这个如下:
On Client side I'm trying this below:
var comment = { ID: 0, Text: $('#text').val(), Author: $('#author').val(), Email: $('#email').val(), GravatarUrl: '' };
var json = JSON.stringify(comment);
$.getJSON("api/MintEIQAPI/" + json,
问题是GetBenchMarkData动作不会被调用上面的getJSON查询。
The problem is the GetBenchMarkData action never gets called with above getJSON query.
可能有人请帮助我,我在做什么错了?
Could someone please help me, what I'm doing wrong?
感谢。
推荐答案
的问题是,的getJSON
执行 GET
请求到服务器。对于传递整个对象,您必须执行 POST
要求
The problem is that getJSON
executes a GET
request to the server. For passing in entire objects, you have to execute a POST
request.
在一个GET ,JavaScript对象传递给jQuery的阿贾克斯在情况下调用通常会被转化为URL连接然后可以通过你的服务器端采取单独codeD参数方法像
In the case of a GET, the JavaScript object you pass to the jQuery Ajax calls will normally be transformed into URL encoded parameters which could then be taken individually by your server-side method like
$.ajax({
url: "/someurl/getbenchmarkdata",
data: JSON.stringify({ filterValue: "test" }),
type: "GET"
...
});
和在你的服务器端
public SomeObject GetBenchMarkData(String filterValue)
{
...
}
相反,如果您想要传送整个对象,您应该执行Ajax调用作为POST,像
Instead, if you want to transmit a whole object, you should execute the ajax call as a POST, like
$.ajax({
url: "/someurl/benchmarkdata",
type: "POST",
data: JSON.stringify({ title: "My title"}),
dataType: "json",
contentType: "application/json; charset=utf-8",
...
});
和服务器端方法必须采用一个对象类型字符串
的属性标题
。
And your server-side method must take an object with a property Title
of type String
.
这篇关于ASP.NET的WebAPI - 如何传递对象,$ .getJSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!