2010-11-12 72 views
0

比方說,我已經在波紋管模型ASP.NET MVC如何綁定List <T>類型的屬性?

public class UserInformation 
{ 
    public List<UserInRole> RolesForUser { get; set; }  
    //Other properties omitted... 
} 

public class UserInRole 
{ 
    public string RoleName { get; set; } 
    public bool InRole { get; set; } 
} 

在我的網頁我有類似

<%using(Html.BeginForm()){%> 
    .../... 
    <%for(int i =0; i<Model.InRoles.Cout; i++%> 
    <p><%: Html.CheckBox(Model.Roles[i].RoleName, Model.Roles[i].InRole)%></p> 
<%}%> 

的想法是能夠檢查/取消選中該複選框,這樣,當窗體發佈通過在每個角色中添加/刪除用戶,操作可以適當地執行。

問題是當表單發佈到操作方法時,Roles屬性(它是一個列表UserInRole對象)不反映用戶所做的更改。 ModelBinder適用於所有其他屬性,但'角色屬性'

我想知道我該怎麼做。我懷疑賦予複選框的名稱/ ID不合適。但是,我只是堆棧。也許我應該以不同的方式做。

感謝您的幫助

+0

[複雜模型綁定到一個列表(的可能重複http://stackoverflow.com/questions/231878/complex-model-binding-to-a -list) – jfar 2010-11-12 13:04:58

回答

2

您應該看到model binding to a list菲爾哈克的帖子。 基本上你需要的只是提交一堆表單域,每個表單域都有相同的名字。

<%@ Page Inherits="ViewPage<UserInformation>" %> 

<% for (int i = 0; i < 3; i++) { %> 

    <%: Html.EditorFor(m => m.RolesForUser[i].RoleName) %> 
    <%: Html.EditorFor(m => m.RolesForUser[i].InRole) %> 

<% } %> 
+0

好吧,這比我想象的要容易得多。非常感謝。 – Richard77 2010-11-12 10:59:33

+0

請檢查我的問題。現在我正在檢查你的答案,我看到你讓頁面繼承IList 。但該模型是UserInformation,其中包含List 。因爲我嘗試了你的建議,但我仍然得到空值。 – Richard77 2010-11-12 12:41:06

+0

嘗試使用m => m.RolesForUser [i] – 2010-11-12 13:21:36

1

我認爲問題在於如何提交表單數據。對於模型綁定來說,它需要鍵名和相關的值。根據你的代碼應該正確綁定下面的代碼:

<%using(Html.BeginForm()){%> 
    .../... 
    <%for(int i =0; i<Model.RolesForUser.Count; i++%> 
    <p> 
    <%: Html.Hidden("UserInformation.RolesForUser[" + i + "].RoleName", Model.RolesForUser[i].RoleName) %> 
    <%: Html.CheckBox("UserInformation.RolesForUser[" + i + "].InRole", Model.RolesForUser[i].InRole) %> 
    <%: Model.RolesForUser[i].RoleName %> 
    </p> 
<%}%> 
+0

有趣!只有一件事。你爲什麼使用Html.Hidden? – Richard77 2010-11-12 11:03:57

+0

爲了完整性,我包含了RoleName屬性,但當然如果您擔心被篡改的值,可能會忽略它。 – 2010-11-12 11:20:31

+0

列表仍然爲空。 – Richard77 2010-11-12 12:37:02