2015-04-22 41 views
0

我已經研究過所有的網絡,但希望在這裏有人可以幫助我。ASP.NET MVC5 Model Binder - 綁定集合集合時爲空

我有以下視圖模型類:

public class PersonEditViewModel 
{ 
    public Person Person { get; set; } 
    public List<DictionaryRootViewModel> Interests { get; set; } 
} 

public class DictionaryRootViewModel 
{ 
    public long Id { get; set; } 
    public string Name { get; set; } 
    public ICollection<DictionaryItemViewModel> Items; 

    public DictionaryRootViewModel() 
    { 
     Items = new List<DictionaryItemViewModel>(); 
    } 
} 

public class DictionaryItemViewModel 
{ 
    public long Id { get; set; } 
    public string Name { get; set; } 
    public bool Selected { get; set; } 
} 

在編輯視圖我使用自定義EditorTemplate使用@Html.EditorFor(m => m.Interests)興趣的佈局集合。有兩個EditorTemplates是做渲染:

  1. DictionaryRootViewModel.cshtml:

    @model Platforma.Models.DictionaryRootViewModel 
    @Html.HiddenFor(model => model.Id) 
    @Html.HiddenFor(model => model.Name) 
    @Html.EditorFor(model => model.Items) 
    
  2. DictionaryItemViewModel.cshtml:

    @model Platforma.Models.DictionaryItemViewModel 
    @Html.HiddenFor(model => model.Id) 
    @Html.CheckBoxFor(model => model.Selected) 
    @Html.EditorFor(model => model.Name) 
    

問題:

使用POST提交表單時,只有Interests集合會被填充,並且Interest.Items集合始終爲空。 請求包含(除其他外)以下字段名稱,它們在檢查控制器操作方法中的Request.Forms數據時也存在。

  • 興趣[0] .ID
  • 興趣[0]請將.Name
  • 興趣[0] .Items [0] .ID
  • 興趣[0] .Items [0] .Selected

所有包含適當的值 - 但在控制器側中,對象在PVM方法:

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Edit(PersonEditViewModel pvm) 
{ 
} 

包含Interests集合中的數據(具有正確ID和名稱的項目),但是對於集合的每個元素,其'Item的子集合爲空。

我該如何正確選擇模型?

+0

不是很熟悉MVC,但也許你的模型必須是[Serializable接口] – Suhan

回答

1

像往常一樣 - 答案一直在我面前。 的DefaultModelBinder沒有拾起在請求中傳遞,因爲我「忘記」標記項目集合作爲屬性中的項目值 - 這是一個領域! 正確的形式,考慮到@pjobs有用的話:

public List<DictionaryItemViewModel> Items{獲取;集;}

+0

:),我認爲這只是速記,應該指出它 – pjobs

0

大部分時間問題都與索引有關,如果您有收藏發佈,您需要有順序索引或者如果索引不是順序的,則需要具有Interests [i] .Items.Index隱藏字段。

Here is similar question on SO

它將工作,如果你有

Interests[0].Id 
Interests[0].Name 
Interests[0].Items[0].Id 
Interests[0].Items[0].Selected 
Interests[0].Items[2].Id 
Interests[0].Items[2].Selected 

因此,要解決它,你要麼確保有序貫指標作爲

Interests[0].Id 
Interests[0].Name 
Interests[0].Items[0].Id 
Interests[0].Items[0].Selected 
Interests[0].Items[1].Id 
Interests[0].Items[1].Selected 

OR

Interests[0].Id 
Interests[0].Name 
Interests[0].Items.Index = 0 (hidden field) 
Interests[0].Items[0].Id 
Interests[0].Items[0].Selected 
Interests[0].Items.Index = 2 (hidden field) 
Interests[0].Items[2].Id 
Interests[0].Items[2].Selected 
+0

嗨,謝謝你的幫助!不幸的是,它似乎並不奏效。第一種方法已經實現了,因爲我使用了ASP.NET MVC5的內置模板功能。我試了另一個,結果是一樣的。 – Rax

+0

我們可以看到更多的信息,從您的回傳,我的意思是你Request.Forms數據萬物 – pjobs

+0

另一件事是,你可以改變公衆的ICollection 產品以公開名單在您的視圖模型,並嘗試 – pjobs