【问题标题】:Unable to retrieve selected value in DropDownList in ASP.NET MVC?无法在 ASP.NET MVC 的 DropDownList 中检索选定的值?
【发布时间】:2019-10-06 18:48:23
【问题描述】:

试图在 ASP.NET MVC 中检索我的 DropDownList 的选定值。我正在使用以下代码:

HTML

 grid.Column("Other", header: "Other", format: @<text>@Html.DropDownList("OtherKey", (IEnumerable<SelectListItem>)ViewBag.OtherKeysList, new { @class = "extra-class" })</text>)))

结果如下:

尝试使用以下代码检索我的 DropDownList 的选定值(在本例中为:otherkey3、otherkey2、otherkey1):

 <script type="text/javascript">

       var dict = [];

       $('#btnSubmit').click(function (e) {
           $('#tableID  > tbody  > tr >  td').each(function () {
               $('#OtherKey > option').each(function () {
                   console.log(($(this).val()));
               });
           });
       });

   </script>

但这不起作用,我得到以下输出:

有人看到我做错了吗?

提前致谢!

【问题讨论】:

    标签: javascript jquery loops drop-down-menu webgrid


    【解决方案1】:

    这里有几个问题。首先,您将获得每个 &lt;option&gt; 的值,因此它将始终返回所有选项,无论是选择的还是其他的。在&lt;select&gt; 本身上使用.val() 来获取当前选择的值:

    console.log($('#OtherKey').val());
    

    但是,您似乎也在 HTML 中重复使用 OtherKey ID。看看您的服务器端代码生成的实际 HTML。如果 ID 不是唯一的,那么使用这些 ID 的 JavaScript 代码的行为是未定义的。

    您的元素确实使用了class,因此您可以使用它。 (如果这些元素不是唯一的,那么您可以为它们分配一个额外的类。)像这样:

    $('.extra-class').each(function () {
        console.log(($(this).val()));
    });
    

    还请注意,您不需要通过&lt;select&gt; 元素循环遍历表格行,后者就可以了。除非您出于此处未显示的其他原因特别需要识别表行。

    【讨论】:

      猜你喜欢
      • 2013-03-30
      • 2018-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-21
      相关资源
      最近更新 更多