3

ASPNET 4.5 Web フォームで新しい ModelBinding 機能を使用しようとしていますが、うまくいきません。

フォームを送信した後、何らかの理由で Contact.ContactType が null のままです。

モデル:

public class Contact
{
    public int ContactId { set; get; }
    public string Name { set; get; }
    public string Phone { set; get; }

    public ContactType ContactType { set; get; }
}

public class ContactType 
{
    public int ContactTypeId { set; get; }
    public string Description { set; get; }

public virtual ICollection<Contact> Contacts { set; get; }
}

ASPX:

<asp:FormView ID="FormView1" runat="server"
    ItemType="Models.Contact" DataKeyNames="ContactId" 
     DefaultMode="Insert" InsertMethod="InsertContact" >
    <InsertItemTemplate>
        <ul>
            <li>
                <label>Name</label>
                <asp:DynamicControl runat="server" id="Name" DataField="Name" Mode="Insert" />
            </li>
            <li>
                <label>Phone</label>
                <asp:DynamicControl runat="server" id="Phone" DataField="Phone" Mode="Insert"  />
            </li>
            <li>
                <label>Contact Type</label>
                <asp:DropDownList ID="ContactType" runat="server" AppendDataBoundItems="true"
                    ItemType="Models.ContactType" SelectMethod="GetContactTypes"
                    DataTextField="Description" DataValueField="ContactTypeId">
                    <asp:ListItem Value="0" Text="Select"></asp:ListItem>
                </asp:DropDownList>
            </li>
            <li>
                <asp:LinkButton ID="LinkButton1" runat="server"
                    CommandName="Insert" Text="Insert" >

                </asp:LinkButton>
            </li>
        </ul>
    </InsertItemTemplate>
</asp:FormView>

ASPX.CS:

public void InsertContact(Contact contact)
    {
        if (ModelState.IsValid)
        {
            // Save changes here
        }
    }

ドロップダウン/リストボックスで ModelBinding を正常に使用するにはどうすればよいですか?

4

1 に答える 1

6

getcontacttypes で Dictionary を返し、次を使用できます。

    <asp:DropDownList ID="ContactType" runat="server" AppendDataBoundItems="true"
       SelectMethod="GetContactTypes"
      DataTextField="Value" DataValueField="Key"
      SelectedValue="<%# BindItem.ContactTypeId%>"
      >
      <asp:ListItem Value="0" Text="Select"></asp:ListItem>
    </asp:DropDownList>

SelectedValue="<%# BindItem.ContactTypeId%>" が重要

于 2012-12-18T19:37:24.853 に答える