2011-11-06 62 views
0

這裏是我的控制器:ASP.NET DefaultModelBinder沒有約束力JSON對象集合

public class TagsController : Controller 
{ 
    public ActionResult Attach(TagsAttach model) 
    { 
    // ... 
    } 
} 

這裏是我的看法,型號:

public class TagsAttach 
{ 
    public int GroupID { get; set; } 
    public List<Tag> Tags { get; set; } 
} 

public class Tag 
{ 
    public int ID { get; set; } 
} 

而這裏的,我使用的Javascript代碼試圖提交我的數據:

var data = { 
    GroupID: 12, 
    Tags: [] 
}; 

data.Tags.push({ ID: 3 }); 
data.Tags.push({ ID: 4 }); 

$.push('/Tags/Attach', data); 

但是,當我調試我的控制器動作時,我發現一切都在那裏exc ept獲取每個Tag對象中的ID值。

因此,我的 '模式' 參數如下:

model 
    GroupID 12 
    Tags 
    Tag 
     ID 0 
    Tag 
     ID 0 

這是爲什麼?我必須爲ASP.NET MVC做些什麼來正確綁定我的ID值?

(注:?我在做什麼,似乎幾乎完全一樣this那麼,爲什麼不是爲我工作)

回答

2

經進一步檢查,看來這是不可能的,因爲'$ .post'使用的jQuery JSON處理器與ASP.NET MVC中的DefaultModelBinder之間的基本不兼容。

基本上,我可以得到模型綁定,如果我模仿一個帖子在小提琴手如下數據(序列化也行,當然)工作:

SearchTagID=1&ApplicationType=0&Items[0].ID=2&Items[1].ID=672 

注意,它使用「點」符號,例如:Items [0] .ID = 2。

jQuery的代碼是用「方括號」標記,如下:

SearchTagID=1&ApplicationType=0&Items[0][ID]=2&Items[1][ID]=672 

所以,除非有辦法讓jQuery的使用點符號代替,我想我得找出一些一種解決方法。

3

ASP.NET MVC 3有一個內置的JsonValueProviderFactory它允許你發送JSON請求到控制器動作,默認的模型聯編程序將能夠將這個JSON字符串轉換爲相應的視圖模型。你可以使用$.ajax方法是這樣的:

var dataToSend = { 
    // model is the name of the action parameter 
    // this nesting could be omitted 
    model: { 
     GroupID: 12, 
     Tags: [ { ID: 3 }, { ID: 4 } ] 
    } 
}; 

// the following will also work but assumes that you have a single 
// action argument. And since your actions should take only the view model 
// as action argument it is also a good way: 
// var dataToSend = { GroupID: 12, Tags: [ { ID: 3 }, { ID: 4 } ] }; 

$.ajax({ 
    url: '@Url.Action("Attach", "Tags")', 
    type: 'POST', 
    contentType: 'application/json; charset=utf-8', 
    data: JSON.stringify(dataToSend), 
    success: function(result) { 
     alert('success'); 
    } 
}); 

這使您可以發送任意複雜的JavaScript文字到控制器的動作。

重要講話:

  • contentType: 'application/json; charset=utf-8'設置Content-Type要求標頭,以使服務器知道我們發送的是JSON請求。

  • JSON.stringify是一種將JavaScript文字串行化爲JSON字符串的方法。這種方法原生地構建到現代瀏覽器中,但如果您需要支持傳統瀏覽器,則可以將json2.js腳本包括到您的頁面中。