2016-11-22 82 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); 
      } 

     }); 
    }