【问题标题】:DropDownList.SelectedItem.Text - html is not marking selected=selected c#DropDownList.SelectedItem.Text - html 没有标记 selected=selected c#
【发布时间】:2018-08-22 15:38:50
【问题描述】:

我将 DropDownList 与数据绑定,并根据值选择选项。

如果我选择带有值的 DropDownList,一切正常。这意味着如果我这样做 selectedValue 然后它会在前端显示选择,它还会在 HTML 中显示“selected=selected”。但是如果我使用 SelectedItem.Text 那么它只会在前端显示选择,但 HTML 不会在 HTML 中标记 slected=selected。

我希望 HTML 在 HTML 中标记 selected=selected,以便我可以在代码中使用选定的值。

请在下面查看我的代码以及选定的值,它按预期工作:

DepartmentList.DataTextField = "Title";
DepartmentList.DataValueField = "Id";
DepartmentList.SelectedValue = DepartmentID; 
DepartmentList.DataSource = resultLoc.OrderBy(item => item.Title);
DepartmentList.DataBind();

请看截图:

https://snag.gy/VSmz48.jpg

请在下面使用所选名称查看我的代码,它无法正常工作,因为它在下拉列表中显示名称为已选择,但未在 HTML 中标记 selcted=selcted。

请在下面使用所选名称查看我的代码,但它不起作用:

DepartmentList.DataTextField = "Title";
DepartmentList.DataValueField = "Id";
DepartmentList.SelectedItem.Text = DepartmentName; // Finance
DepartmentList.DataSource = resultLoc.OrderBy(item => item.Title);
DepartmentList.DataBind();

请看截图:

https://snag.gy/hok3FV.jpg

【问题讨论】:

  • 代替DepartmentList.SelectedItem.Text = DepartmentName;试试DepartmentList.Items.FindByText(DepartmentName).Selected = true;
  • @SuprabhatBiswal 如果我这样做,它甚至不会绑定下拉列表。
  • DepartmentList.SelectedItem.Text = DepartmentName;这是将所选项目的文本设置为部门名称。绝对不是你想要的!
  • @TheSoftwareJedi 我希望下拉菜单显示部门名称,并且它应该在 html 中标记 selected=selected 以便我可以使用该值
  • @orbnexus 看看我的回答。

标签: c# asp.net data-binding html-select dropdown


【解决方案1】:

作为新成员,对 cme​​ts 的声誉并不高,试图通过在 SO 中上面的 cmets 中提到的一些研究来提供帮助,并找到了这个答案。请试试这个 -

DepartmentList.Items.FindByText(DepartmentName).Selected = true;

How can you set the selected item in an ASP.NET dropdown via the display text?

how to select with DropDownList.text

以及此处对 Text 和 Value 属性的说明。

SelectedValue vs SelectedItem.Value of DropDownList

【讨论】:

    【解决方案2】:

    这就是你想要做的:

    DepartmentList.SelectedValue = DepartmentList.Items.FindByText(DepartmentName).Value;
    

    更多详情请参阅this nearly identical question

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-14
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      • 2012-09-28
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      相关资源
      最近更新 更多