简体   繁体   English

在MVC中通过Jquery从隐藏字段中获取多个值

[英]Get multiple values from a hidden field through Jquery in MVC

I am trying to use a hidden field control in my in a foreach loop where am binding multiple values in the hidden field value in this way我试图在我的 foreach 循环中使用隐藏字段控件,其中以这种方式绑定隐藏字段值中的多个值

@foreach(var category in Model)
{
<input type="hidden" Id="hdnCategory" value="@category.Id"/>
}

Now using Jquery I am trying to retrieve the value.现在使用 Jquery 我试图检索该值。 But the result is not as expected.但结果并不如预期。 It is actually retrieving the first value from the foreach它实际上是从 foreach 中检索第一个值

 function btnClick() {
     var categoryID = $("#hdnCategory").val();      
}

This function am calling in a button click in this way此功能正在以这种方式调用按钮单击

<img class="imageclass"src="listofImages" onclick="imageClick()" />

Can someone please suggest me where I am going wrong..有人可以建议我哪里出错了..

You can try below你可以试试下面

Also i think your function name is different我也认为你的函数名称不同

@foreach(var category in Model)
{
    <input type="hidden" Id="hdnCategory" class="csscategory" value="@category.Id"/>
}

<img class="imageclass" src="listofImages" onclick="imageClick()" />

 function imageClick() { $("input.csscategory").each(function() { var val = $(this).val(); }); }

所有这些隐藏字段都具有相同的id因此 jQuery(以及带有querySelector vanilla JavaScript)只返回第一个。

When referencing tag with ID only first one is fetched because ID is supposed to be unique.当引用带有 ID 的标签时,只获取第一个标签,因为 ID 应该是唯一的。

For your code to work change ID attribute to class attribute then loop through elements and fetch value.为了让您的代码工作,将 ID 属性更改为类属性,然后循环遍历元素并获取值。

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <img class="imageclass" src="listofImages" /> <input type="hidden" class="hdnCategory" value="@category.Id" /> <input type="hidden" class="hdnCategory" value="@category.Id2" />... <script> $(document).ready(function() { $('.imageclass').click(function() { $(".hdnCategory").each(function() { var val = $(this).val(); //do some thing with val alert(val); }); }); }); </script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM