2010-08-19 59 views
0

我試圖在選擇下拉列表時填寫說明字段。我得到它的工作,但我不能使用Json內容類型。這個作品Json contentType:將jquery POST分配給MVC控制器

<script type="text/javascript"> 
    $(document).ready(function() { 
     $("#ddl_id").change(function() { 
      var test = $("#ddl_id").val(); 
      $.ajax({ 
       type: "POST", 
       url: "<%= Url.Action("GetVal") %>", 
       data: {id: test}, 
       //contentType: "text/plain", 
       dataType: "json", 
       success: function(result) { 
        $("#serial").val(result); 
       }, 
       error: function(e) { 
        alert(e); 
       } 
      }); 
     }); 
    }); 

</script> 

但是當我取消註釋的contentType:我得到空返回到我的控制器。我也試着

contentType: "application/json; charset=utf-8", 

這是我的控制器

[HttpPost] 
    public JsonResult GetVal(string id) 
    {....... 

爲什麼,當我有我的contentType得到空過去了?什麼是編碼Json數據的最佳方法?我在這方面是全新的,我找不到一個簡單的解釋。

回答

2
$.ajax({ 
     type: "POST", 
     url: "<%= Url.Action("GetVal") %>", 
     data: JSON.stringify({id: test}), 
     contentType: "application/json", 
     dataType: "json", 
     success: function(result) { 
      $("#serial").val(result); 
     }, 
     error: function(e) { 
      alert(e); 
     } 
}); 

這個函數的一個問題是指定一個JSON contentType實際上並不會導致jQuery對您的請求進行JSON編碼。您必須手動執行此操作,否則它將被序列化爲application/x-www-form-urlencoded

您需要json2和/或本機JSON。

+0

感謝您的答覆,但我厭倦了你給我,我在控制器中仍然無法獲得Null。該帖子有{「ID」:「string」},但它仍然在服務器端顯示爲空。 – Peter 2010-08-19 04:24:17

0

在服務器端,使用一個對象來獲取參數值。 像:

public class sealed MyClass{ 
    public Int32 ID{get;set;} 
    // other properties here... 
} 

[HttpPost] 
public ActionResult MyAction(MyClass mycls){ 
    // here your can get the property,like 
    mycls.ID; 
} 

您可以閱讀閱讀MSDN博客操作方法使用

Introducing ASP.NET MVC 3 (Preview 1)

相關問題