无法在 ASP.NET MVC 的 DropDownList 中检索选定的值?

尼尔斯斯坦登

试图在 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>

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

在此处输入图片说明

有没有人看到我做错了什么?

提前致谢!

大卫

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

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

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

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

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

还需要注意的是你没有在表中的行需要循环,并通过<select>元素,只是后者是罚款。除非您出于此处未显示的其他原因特别需要标识您的表格行。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

ASP.NET MVC中的DropdownList-未发布值

如何使用所需的验证创建ASP.Net MVC DropDownList

ASP.Net MVC5中DropDownlist的困难

使用CHOSEN在MVC ASP.Net中可搜索的DropDownList

无法设置通过ASP.NET MVC中的模型传递的jQuery生成的dropdownlist选定值

如何在ASP.NET MVC中创建可搜索的DropDownList

在ASP.Net中的GridView EditItemTemplate中设置DropDownList选定值

如何在ASP.NET Core MVC App中获取DropDownList的选定值

DropDownList值转换为DataType.Date模型(ASP.NET MVC 4)

ASP.NET MVC DropDownList替代

如何从模型设置ASP.NET MVC DropDownList的默认值

Asp.net MVC5引导程序:无法在编辑页面下拉列表中获取选定的值

c#ASP.net MVC中的DropDownlist和列表问题

从数据库传递值到ASP.net MVC 4中的DropDownList中的视图

ASP.Net MVC DropDownList编辑器模板

ASP.NET MVC的层叠DropDownList

ASP.NET MVC @ Html.DropdownList对于错误的选定值

ASP.NET MVC DropDownList NullReferenceException

ASP.NET MVC值不能为null。在DropDownList上

DropDownList中的SelectedValue无法选择任何值(VB.Net,Asp.Net)

使用asp.net mvc将DropDownList中的SelectedValue从View Razor传递到控制器

ASP.NET MVC中的Dropdownlist onchange事件未使用AJAX

ASP.NET MVC在编辑时将数据库值检索到DropDownList

ASP.NET MVC从数据库检索数据到DropDownList

在asp.net MVC中为dropdownlist创建列表

如何在 ASP.Net MVC 中显示多个 DropDownList 并获取值

从 AJAX (ASP.NET MVC) 填充 DropdownList

在 ASP.NET MVC 中填充 DropDownList

在 ASP.NET Core 的 @Html.Dropdownlist 中禁用选定的值