minoyo
minoyo

Reputation: 95

Pass c# variable parameter in a onClick function

I´m working with MVC razor and I have a small issue in the view part...

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...

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"...

thanks in advance for the Help!

Upvotes: 3

Views: 13613

Answers (4)

Rashad Valliyengal
Rashad Valliyengal

Reputation: 3162

try this

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

Upvotes: 0

K D
K D

Reputation: 5989

If your value is not an integer then you have to use it like following

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

Upvotes: 3

Jaimin
Jaimin

Reputation: 8020

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.
      }

Upvotes: 0

Darren
Darren

Reputation: 70728

You are creating multiple input's with the same ID (request). HTML ID's should be unique.

As an alternative approach to what you require, you could use a data-attribute

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

And use jQuery to handle which ID you need:

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

http://jsfiddle.net/XAffc/

Upvotes: 3

Related Questions