使用 MVC 4 API 控制器 POST JSON [英] POST JSON with MVC 4 API Controller
本文介绍了使用 MVC 4 API 控制器 POST JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个代码:
$.ajax({
type: "POST",
url: "/api/slide",
cache: false,
contentType: "application/json; charset=utf-8",
data: '{"Title":"fghfdhgfdgfd"}',
dataType: "json",
这是我的控制器:
public class SlideController : ApiController
{
// POST /api/Slide
public void Post(string Title)
{
}
当我运行代码并调用/api/Slide时,[Title]没有数据并且为空.
When I run the code and call the /api/Slide, the [Title] has no data and is null.
如何将 JSON 发布到 API 控制器?
How do I post JSON to the API controller?
POST http://127.0.0.2:81/api/slide HTTP/1.1
Host: 127.0.0.2:81
Connection: keep-alive
Content-Length: 18
Origin: http://127.0.0.2:81
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1
Content-Type: application/json; charset=UTF-8
Accept: application/json, text/javascript, */*; q=0.01
Referer: http://127.0.0.2:81/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Title=fghfdhgfdgfd
推荐答案
定义一个视图模型:
public class SlideViewModel
{
public string Title { get; set; }
}
然后让您的控制器操作将此视图模型作为参数:
then have your controller action take this view model as argument:
public class SlideController : ApiController
{
// POST /api/Slide
public void Post(SlideViewModel model)
{
...
}
}
最后调用动作:
$.ajax({
type: 'POST',
url: '/api/slide',
cache: false,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ title: "fghfdhgfdgfd" }),
success: function() {
...
}
});
这样做的原因是像字符串这样的简单类型是从 URI 绑定的.我还邀请您阅读 以下文章关于 Web API 中的模型绑定.
The reason for that is that simple types such as strings are bound from the URI. I also invite you to read the following article about model binding in the Web API.
这篇关于使用 MVC 4 API 控制器 POST JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文