ASPNET 4.5 WebForms ModelBinding不能与DropDownList一起使用

时间:2012-11-15 21:07:39

标签: webforms

我正在尝试在ASPNET 4.5 Webforms中使用新的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?

1 个答案:

答案 0 :(得分: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 =“&lt;%#BindItem.ContactTypeId%&gt;”很重要