【问题标题】:ASPNET 4.5 WebForms ModelBinding not working with DropDownListASP NET 4.5 Web 窗体模型绑定不适用于 DropDownList
【发布时间】:2012-11-15 21:07:38
【问题描述】:

我正在尝试在 ASPNET 4.5 Webforms 中使用新的 ModelBinding 功能,但没有成功。

由于某种原因,Contact.ContactType 在提交表单后仍然为空。

型号:

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?

【问题讨论】:

  • 问题解决了吗?如果答案对您有所帮助,您应该将其宣传为正确的或选择发布最佳方法。

标签: webforms


【解决方案1】:

您可以在 getcontacttypes 中返回字典,然后使用:

    <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="" 很重要

【讨论】:

    猜你喜欢
    • 2013-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-04
    • 2018-06-21
    • 2014-07-29
    • 2012-09-10
    • 1970-01-01
    相关资源
    最近更新 更多