I'm trying to use the new ModelBinding feature in ASPNET 4.5 Webforms without success.
For some reason Contact.ContactType remains null after submitting the form.
Model:
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
}
}
How do I get to use ModelBinding on a dropdown/listbox successfully?
You could return a Dictionary in getcontacttypes and then use:
<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%>" is important
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With