2013-10-31 51 views
1

我有一个jquery Ajax调用更多的还是像下面网页API MVC结合FormDataCollection

$.ajax(url, { 
     type: httpMethod, 
     contentType: "application/json; charset=utf-8", 
     data: '{name:"abc",age:23,address:"29 judd ce"}', 

的网页API动作

public HttpResponseMessage Post([FromBody] FormDataCollection data) 
     { 

但是参数 '数据' 总是空。

这是一个Web API的限制还是我做了错误的方式

感谢

回答

1

使用视图模型来代替:

public class UserViewModel 
{ 
    public string Name { get; set; } 
    public int Age { get; set; } 
    public string Address { get; set; } 
} 

您的控制器的行动将采取:

public HttpResponseMessage Post(UserViewModel model) 
{ 
    ... 
} 
+0

分隔嗨Darin想知道如果有没有使用viewmodel的方式? – josephj1989

+0

您可以随时从请求中读取数据或编写一些自定义绑定程序或其他内容,但如果您已经将所需的所有内容都直接构建到框架中,那么这种方法会非常疯狂。 –

0

有可能

$.ajax("http://localhost:57281/api/Values", { 
        type: "POST", 
        data: '{name:"abc",age:23,address:"29 judd ce"}', 
        contentType: "application/x-www-form-urlencoded" 
       }); 



//POST api/values 
public void Post([FromBody]FormDataCollection value) 
{ 

} 

而且工作没有[FromBody] 但是你只能得到一对键/值的

更好地利用类似的东西

$.ajax("http://localhost:57281/api/Values", { 
        type: "POST", 
        data: 'name=abc&age=23&address=29 judd ce', 
        contentType: "application/x-www-form-urlencoded" 
       }); 

&用作每对