asp.net – AJAX将多个参数传递给WebApi
AJAX请求:
$.ajax({ url: url,dataType: 'json',type: 'Post',data: {token:"4",feed:{"id":0,"message":"Hello World","userId":4} } }); 服务器端Web API: [HttpPost] public HttpResponseMessage Post(string token,Feed feed) { /* Some code */ return new HttpResponseMessage(HttpStatusCode.Created); }
为什么我收到此错误以及为什么我无法将多个参数POST到我的API? 解决方法
首先编写视图模型:
public class MyViewModel { public string Token { get; set; } public Feed Feed { get; set; } } 您的控制器操作将作为参数: [HttpPost] public HttpResponseMessage Post(MyViewModel model) { /* Some code */ return new HttpResponseMessage(HttpStatusCode.Created); } 最后调整你的jQuery调用将其作为JSON发送: $.ajax({ url: url,type: 'POST',contentType: 'application/json',data: JSON.stringify({ token: '4',feed: { id: 0,message: 'Hello World',userId: 4 } }) }); AJAX调用需要注意的重要事项: >将请求contentType设置为application / json>将数据包装在JSON.stringify函数中,以有效地将javascript对象转换为JSON字符串>删除无用的dataType:’json’参数. jQuery将自动使用服务器发送的Content-Type响应头来推断如何解析传递给成功回调的结果. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- asp.net-mvc-4 – 为什么我们需要MVC中的Web API? mvc中re
- asp.net – RequireNonLetterOrDigit未正确验证
- 启动asp.net输出缓存
- asp.net – 带有requireSSL for cookies的Sitecore
- ASP.NET 5中的全局异常处理
- asp.net – “共享主机中的”LOG_BACKUP“的数据库的事务日
- asp.net-mvc – 在哪里可以找到与asp.net MVC一起使用的优秀
- asp.net – WebApi:如何处理图像
- asp.net-core – ASP.NET Core Web Application控制台立即关
- ASP.NET有一个复选框列表,在4×5网格中有我很好的复选框