2014-01-29 38 views
0

我一直在使用Web API,发现了一个有趣的观察,我无法理解。为什么ModelBinding不能与FormData一起使用,但可以与RequestPayload一起使用?

控制器:

 
public class UserController: ApiController 
{ 
    public void Post(MyViewModel data) 
    { 
     //data is null here if pass in FormData but available if its sent through Request Payload 
    } 
} 

视图模型

 
public class MyViewModel{ 
     public long SenderId { get; set; } 
     public string MessageText { get; set; }  
     public long[] Receivers { get; set; } 
} 

JS不工作

 
var usr = {}; 
usr.SenderId = "10"; 
usr.MessageText = "test message"; 
usr.Receivers = new Array(); 
usr.Receivers.push("4"); 
usr.Receivers.push("5"); 
usr.Receivers.push("6"); 

$.ajax(
{ 
    url: '/api/User', 
    type: 'POST', 
    data: JSON.stringify(usr), 
    success: function(response) { debugger; }, 
    error: function(error) {debugger;} 
}); 

JS是工作

 
var usr = {}; 
usr.SenderId = "10"; 
usr.MessageText = "test message"; 
usr.Receivers = new Array(); 
usr.Receivers.push("4"); 
usr.Receivers.push("5"); 
usr.Receivers.push("6"); 

$.post("/api/User", usr) 
.done(function(data) { 
debugger; 
});

因此,如果我传递$.ajax与其他很多配置如type,contentType,accept等,它仍然没有正确绑定模型,但在$.post的情况下它的工作原理。

任何人都可以解释为什么?

+0

什么是基于请求,并在'$ .post'的情况下,你看到在'$ .ajax'情况下,内容类型?请注意,内容类型对web api非常重要,因为它尝试使用基于此的正确格式化程序来反序列化请求内容。 –

+0

内容类型是application \ json,我想知道它为什么适用于请求负载而不适用于表单数据。 –

回答

0

尝试寻找什么被贴的时候你(使用Fiddler例如您选择的F12工具)与$.ajax尝试。很可能是因为jQuery将数据作为URL编码字符串传递,而不是像JSON文本那样传递数据。

要解决此问题尝试contentType参数指定dataType在一起。另外,我不认为你需要JSON.stringify,只是通过JSON文字你创建:

$.ajax({ 
    data: usr, 
    dataType: 'json', 
    contentType: 'application/json', 
    /* The rest of your configuration. */ 
}); 

下面是我们在我们的项目之一使用打字稿方法(ko.toJSON返回表示JSON字符串文字传递作为方法参数):

public static callApi(url: string, type?: string, data?: any): RSVP.Promise { 
    return new RSVP.Promise((resolve, reject) => { 
     $.ajax('/api/' + url, { 
      type: type || 'get', 
      data: data != null ? ko.toJSON(data) : null, 
      dataType: 'json', 
      contentType: 'application/json; charset=utf-8', 
      success:() => { 
       resolve.apply(this, arguments); 
      }, 
      error:() => { 
       reject.apply(this, arguments); 
      } 
     }); 
    }); 
} 

希望这会有所帮助。

+0

我已经做到了。当你通过它通过$就不言而喻申请表数据部分,但是当你把它传递到$。员额它去请求有效载荷部分 –

+0

@PrashantLakhlani不知道你的意思,但只是比较二个原始POST请求,你会立即看到差异。另外,我不认为你需要'JSON.stringify',只是传递你创建的JSON文字。 – volpav

相关问题