DropDownList文本和价值似乎不对

时间:2017-02-06 11:40:08

标签: asp.net

我的代码发生了一些奇怪的事情,我无法弄清楚:

<asp:DropDownList runat="server" ID="ddlMemberType" OnSelectedIndexChanged="ddlMemberType_OnSelectedIndexChanged" AutoPostBack="True"/>
var memberTypeListItems = memberType.Select(x => new KeyValuePair<string, string>(x.GetValue("Name").ToString(), x.GetValue("LongName").ToString()));
ddlMemberType.DataSource = memberTypeListItems;
ddlMemberType.DataBind();
ddlMemberType.DataTextField = "Value"; // No idea why I need to do this but it gets them the wrong way round otherwise
ddlMemberType.DataValueField = "Key";

这会生成以下HTML:

<select name="p$lt$ctl03$pageplaceholder$p$lt$ctl00$pageplaceholder$p$lt$ctl02$BizForm$viewBiz$MembershipCostCalculator$ddlMemberType" onchange="javascript:setTimeout('__doPostBack(\'p$lt$ctl03$pageplaceholder$p$lt$ctl00$pageplaceholder$p$lt$ctl02$BizForm$viewBiz$MembershipCostCalculator$ddlMemberType\',\'\')', 0)" id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_pageplaceholder_p_lt_ctl02_BizForm_viewBiz_MembershipCostCalculator_ddlMemberType">
    <option value="Pharmaceutical">Pharmaceutical company (UK based or overseas)</option>
    <option value="Consultancy">Consultancy (UK based or overseas)</option>
    <option value="Associate">Freelance practitioner (sole trader)</option>
</select>

问题在于所选项目。 ddlMemberType.SelectedItem生成:

Attributes: {System.Web.UI.AttributeCollection}
Enabled: true
Selected: true
Text: "[Pharmaceutical, Pharmaceutical company (UK based or overseas)]"
Value: "[Pharmaceutical, Pharmaceutical company (UK based or overseas)]"

text和value属性完全关闭。甚至用方括号和逗号进行的是什么?另外,为什么键/值对的顺序错误,除非我将DataTextField设置为&#34; Value&#34;和DataValueField到&#34; Key&#34;?

我的数据库中的数据是这样的:

Name    LongName
=====================
Pharmaceutical  Pharmaceutical company (UK based or overseas)
Consultancy Consultancy (UK based or overseas)
Associate   Freelance practitioner (sole trader)

3 个答案:

答案 0 :(得分:3)

您需要交换代码行。文本和值字段的分配应该在数据绑定之前而不是之后发生:

ddlMemberType.DataSource = memberTypeListItems;
ddlMemberType.DataTextField = "Value";
ddlMemberType.DataValueField = "Key";

ddlMemberType.DataBind();

现在的方式,当数据绑定发生时,下拉列表不知道哪个字段是值,哪个是文本,所以它在每个KeyValuePair上调用ToString

另外,要在代码中解决你的注释:你需要告诉DDL如何正确处理正在输入的对象,否则控件不知道对象的哪个属性是&#34; text&#34;一个是&#34;值&#34;一。因此它会尝试使用一些合理的默认值进行猜测,如果您的用例与这些默认值不匹配,则可能会失败。

答案 1 :(得分:1)

在DataBind之前分配DataTextField和DataValueField。

ddlMemberType.DataSource = memberTypeListItems;
ddlMemberType.DataTextField = "Value";
ddlMemberType.DataValueField = "Key";
ddlMemberType.DataBind();

答案 2 :(得分:1)

你的绑定方式是不正确的这样的绑定

var memberTypeListItems = memberType.Select(x => new SelectListItem { Text = x.Name, Value = x.LongName }), "Value", "Text");

并删除这些代码

ddlMemberType.DataTextField = "Value"; 
ddlMemberType.DataValueField = "Key";