简体   繁体   English

在onClick函数中传递c#变量参数

[英]Pass c# variable parameter in a onClick function

I´m working with MVC razor and I have a small issue in the view part... 我正在使用MVC剃须刀,我在视图部分有一个小问题......

To resume, I have a loop with different elements, with each element I have two buttons, one download and another request. 要恢复,我有一个包含不同元素的循环,每个元素我有两个按钮,一个下载和另一个请求。 My problem is with the "request" one... I need that when I click on it, I post the ID of the element... 我的问题是“请求”一个...我需要当我点击它时,我发布元素的ID ...

this is part of my code: 这是我的代码的一部分:

enter code here <div class="contentsection" style="border-bottom:1px solid orange;">
<table style="width:100%;">
    <thead>
       ...
       ...
    </thead>
    <tbody>
        @foreach (DownloadItem di in group.Items)
        {
        <tr>
            <td class="bold">@di.DisplayName</td>
            <td>
                @using (Html.BeginForm("Download", "MyController", new { id = di.ID }, FormMethod.Post, new { style = "display:inline;" }))
                {
                    <input type="submit" id="download" value="Download" />
                }
                    <input type="button" id="request" value="Request" onclick="somejavascriptmethod(@(di.ID))" />
                    <span id="requestDate">@(di.requestDate)</span>                    

            </td>
        </tr>
        }
    </tbody>
</table>

My problem is that when the User click the Button "request", my function "somejavascriptmethod(id)" is called and I need the id as a parameter... ALthough I get a syntac error, I though it could work... but it does not... I dont "post" the id and I get the "500 Internal Server Error"... 我的问题是,当用户单击按钮“请求”时,我的函数“somejavascriptmethod(id)”被调用,我需要id作为参数...虽然我得到一个语法错误,我虽然它可以工作...但它没有...我没有“发布”id,我得到“500内部服务器错误”...

thanks in advance for the Help! 先谢谢您的帮助!

You are creating multiple input's with the same ID ( request ). 您正在使用相同的ID( request )创建多个输入。 HTML ID's should be unique. HTML ID应该是唯一的。

As an alternative approach to what you require, you could use a data-attribute 作为您需要的替代方法,您可以使用data-attribute

<input type="button" data-id="@(di.ID)" value="Request" />

And use jQuery to handle which ID you need: 并使用jQuery来处理您需要的ID:

   $("input[type=button]").click(function() {
      var id = $(this).data("id");
      yourJSFunction(id);
   });

http://jsfiddle.net/XAffc/ http://jsfiddle.net/XAffc/

如果您的值不是整数,那么您必须像下面一样使用它

<input type="button" id="request" value="Request" onclick="somejavascriptmethod('@(di.ID)')" />

Try this, 尝试这个,

 <input type="button" value="Assign" onclick="myfunction(@di.ID);" />

function myfunction(obj) {

        var id = obj;
        alert(id);//this way you can get your id.
      }

尝试这个

 <input type="button" id="request" value="Request" onclick="somejavascriptmethod('@di.ID')" />

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

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