2014-10-27 131 views
0

我试图通过Ajax请求发布我的表单数据,该数据是通过Ajax请求绑定到控制器的,但是,尽管请求标头控制器显示数据为null显示数据正在发送。通过Ajax发布表单数据导致空模型数据

代码如下。我试过数据:JSON.stringify(表单),它导致一个空模型,而下面的结果是一个空数据模型。

查看

$(document).on('click', '#saveData', function() { 
        if ($('#form').valid()) { 
         var form = $('#form').serialize(); 
         $.ajax(
          { 
           url: '@Url.Action("CreateClient", "Processors")', 
           type: 'POST', 
           cache: false, 
           async: false, 
           dataType: 'json', 
           contentType: 'application/json', 
           data: JSON.stringify(form) 
         }) 
          .success(function (response) 
{ alert(response); }) 
          .error(function (response) 
{ alert(response); }); 
        } 
       }); 

控制器

public ActionResult CreateClient(ModelData form) 
    { 
     if (form == null || !ModelState.IsValid) 
     {     
      return Json("Error"); 
     } 

     return Json("Success"); 

    } 

回答

2

有两个问题你的方法。

如果你的模型类ModelData例如,

class ModelData { 
    public string Foo {get;set;} 
    public string Bar {get;set;} 
} 

适当的数据发送是{foo:"foo1", bar:"bar1"},或最终{Foo:"foo1", Bar: "bar1"},这取决于你如何配置你的序列化 - 为您指定的contentType 'application/json'

但是,您正在使用jquery serialize()来阅读您的表单。此方法返回一个字符串,格式为"foo=foo1&bar=bar1",适用于contentType'application/x-www-form-urlencoded'。所以你必须以你想要发送数据的格式作出决定。如果要继续使用serialize()从DOM获取数据,请改用'application/x-www-form-urlencoded'

其次,JSON。 stringify()将从一个对象创建一个JSON字符串。一个字符串也是一个对象。因此,将字符串传递给此函数会将字符串包装为一个字符串,这没有多大意义:数据将类似于"\"foo=foo1&bar=bar1\""。以同样的方式,当contentType为'json'时,jQuery ajax函数将期待一个对象作为它的数据参数,所以如果您之前将对象转换为字符串,它将以如下形式发送:字符串。基本上,无论您最终为您的请求选择contentType,请不要将JSON.stringify用于您的数据参数。

TL; DR:为了得到这个工作,使用默认contentType或明确声明它为每下面,并通过形式变量 - 是:

var form = $('#form').serialize(); 
$.ajax(
    { 
     //(...) 
     contentType: 'application/x-www-form-urlencoded; charset=UTF-8', 
     data: form, 
     //(...)