2016-11-22 80 views
1

我有一个函数将使用AJAX的下拉列表的值传递给控制器​​,控制器然后返回依赖于所选值的数据。MVC到控制器的Ajax POST数据始终为空

问题是一个不断返回任何内容,我可以在该值越来越张贴开发工具见表格数据{"PropertyType":"House"}

调试时PropertyType是不断null当控制器被激发,但似乎无法明白为什么。

AJAX

function PropertyStyleFilter() { 

    var propertyType = $('#PropertyType').val(); 

    var Url = '@Url.Action("PropertyStyleFilter")'; 
    //var Url = '/Case/CaseDetails/PropertyStyleFilter/' + PropertyType; 
    console.log("Property Type:" + PropertyType); 

    $.ajax({ 
     url: Url, 
     data: JSON.stringify({ PropertyType: propertyType }), 
     type: 'POST', 
     success: function (data) { 
      $("#PropertyStyle").html(""); // clear before appending new list 

      $("#PropertyStyle").append($('<option></option>').val("").html("Select Property Style...")); 
      $.each(data, function (i, style) { 
       //console.log(i, site); 
       $("#PropertyStyle").append($('<option></option>').val(style.Value).html(style.Text)); 
      }); 
      if (PropertyType != null) { 
       $("#PropertyStyle").val(PropertyType); 
      } 
     }, 
     error: function (__x, __h, __m) { 
      console.log('ajax returned error', __m, __x, __h); 
     } 

    }); 
} 

控制器

[HttpPost] 
public ActionResult PropertyStyleFilter(string PropertyType) 
{ 
    var StyleList = (from ps in efContext.PropertyStyles 
        join pt in efContext.PropertyTypes 
        on ps.PropertyTypeId equals pt.Id 
        where pt.TypeName == PropertyType 
         orderby ps.Id 
        select new SelectListItem 
        { 
         Value = ps.StyleName, 
         Text = ps.StyleName 
        }); 


    return Json(StyleList, JsonRequestBehavior.AllowGet); 

} 
+1

当您调试JavaScript的,是'propertyType'设置?另外,我不认为有必要在数据对象中使用JSON.stringify(),只需要'data:{PropertyType:propertyType},'将会做 – Luke

+1

你可以添加'dataType:'json''和'contentType :“application/json; charset = utf-8”,'然后再试一次? – Win

+0

这是造成问题的JSON.stringify()...谢谢。 – JBoom

回答

0

尝试,如果这个工程

function PropertyStyleFilter() { 

     var propertyType = $('#PropertyType').val(); 

     var Url = '@Url.Action("PropertyStyleFilter")'; 
     //var Url = '/Case/CaseDetails/PropertyStyleFilter/' + PropertyType; 
     console.log("Property Type:" + PropertyType); 

     $.ajax({ 
      url: Url, 
    dataType: 'json', 
      data: { PropertyType: propertyType }, 
      type: 'POST', 
      success: function (data) { 
       $("#PropertyStyle").html(""); // clear before appending new list 

       $("#PropertyStyle").append($('<option></option>').val("").html("Select Property Style...")); 
       $.each(data, function (i, style) { 
        //console.log(i, site); 
        $("#PropertyStyle").append($('<option></option>').val(style.Value).html(style.Text)); 
       }); 
       if (PropertyType != null) { 
        $("#PropertyStyle").val(PropertyType); 
       } 
      }, 
      error: function (__x, __h, __m) { 
       console.log('ajax returned error', __m, __x, __h); 
      } 

     }); 
    }