AJAX传递多个参数的WebAPI [英] AJAX Passing multiple parameter to WebApi
问题描述
AJAX请求:
$。阿贾克斯({
网址:网址,
数据类型:JSON,
输入:邮报,
数据:{令牌:4,进料:{id为0,信息:你好世界,用户id:4}}
});
服务器端Web API:
[HttpPost]
公众的Htt presponseMessage邮报(字符串标记,供稿)
{
/ *一些code * / 返回新的Htt presponseMessage(的HTTPStatus code.Created);
}
错误code 404:{消息:没有HTTP资源发现匹配
请求URI的'localhost:8080 / API /饲料'。,messageDetail:无动作
控制器上的进与请求匹配被发现。}
块引用>为什么我收到此错误,为什么我不能POST多个参数我的API?
解决方案通过写一个视图模型启动:
公共类MyViewModel
{
公共字符串令牌{搞定;组; }
公共供稿供稿{搞定;组; }
}这是你的控制器操作将作为参数:
[HttpPost]
公众的Htt presponseMessage邮政(MyViewModel模型)
{
/ *一些code * / 返回新的Htt presponseMessage(的HTTPStatus code.Created);
}终于适应你的jQuery呼叫发送为JSON:
$。阿贾克斯({
网址:网址,
输入:POST,
的contentType:应用/ JSON,
数据:JSON.stringify({
令牌:'4',
饲料:{
ID:0,
消息:你好世界
用户名:4
}
})
});重要注意事项的AJAX调用:
- 设置请求
的contentType
到应用程序/ JSON
- 在
JSON.stringify
函数包装数据到JavaScript对象有效转换为JSON字符串- 删除无用的
数据类型:'JSON'
参数。 jQuery将自动使用由服务器发送的内容类型
响应头推断如何解析传递到成功
回调。AJAX request:
$.ajax({ url: url, dataType: 'json', type: 'Post', data: {token:"4", feed:{"id":0,"message":"Hello World","userId":4} } });
Server Side Web API:
[HttpPost] public HttpResponseMessage Post(string token, Feed feed) { /* Some code */ return new HttpResponseMessage(HttpStatusCode.Created); }
Error Code 404: {"message":"No HTTP resource was found that matches the request URI 'localhost:8080/api/feed'.","messageDetail":"No action was found on the controller 'Feed' that matches the request."}
Why I am getting this error and Why I am not able POST multiple parameters to my API?
解决方案Start by writing a view model:
public class MyViewModel { public string Token { get; set; } public Feed Feed { get; set; } }
that your controller action will take as parameter:
[HttpPost] public HttpResponseMessage Post(MyViewModel model) { /* Some code */ return new HttpResponseMessage(HttpStatusCode.Created); }
and finally adapt your jQuery call to send it as JSON:
$.ajax({ url: url, type: 'POST', contentType: 'application/json', data: JSON.stringify({ token: '4', feed: { id: 0, message: 'Hello World', userId: 4 } }) });
Important things to note for the AJAX call:
- setting the request
contentType
toapplication/json
- wrapping the data in a
JSON.stringify
function to effectively convert the javascript object to a JSON string- removed the useless
dataType: 'json'
parameter. jQuery will automatically use theContent-Type
response header sent by the server to deduce how to parse the result passed to thesuccess
callback.这篇关于AJAX传递多个参数的WebAPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!