0

I have a gridview and need to pass two parameters to a javascript function when pressing a button in the gridview. The script is the following:

<script type="text/javascript">
        function AddItem(name,price) {

            javascript: simpleCart.add('name=' + name, 'price=' + price, 'quantity=1');
        }    
    </script>

In the gridview I tried passing the parameters like this:

<asp:Button ID="AddCartButton" runat="server" Text="Add To Cart" onClick="AddCartButton_Click" OnClientClick="AddItem('<%# Eval("Name") %>', '<%# Eval("Price") %>')" />

But got a 'Server tag is not well formed error'.

I also tried like this:

<asp:Button ID="AddCartButton" runat="server" Text="Add To Cart" onClick="AddCartButton_Click" OnClientClick='<%# Eval("Name","Price", "return AddItem({0},{1})") %>'  />

But the Eval function only seems to allow the passing of 1 parameter.

2 Answers 2

2
<asp:Button ID="AddCartButton" runat="server" Text="Add To Cart" onClick="AddCartButton_Click" 
     OnClientClick='<%# Eval("Name", "AddItem(\"{0}\", ").ToString() + Eval("Price", "\"{0}\")").ToString() %>' />
Sign up to request clarification or add additional context in comments.

3 Comments

It works! Thank you very much, been stuck forever! Do you mind explaining why yours worked when the others didn't? Thanks again
It's works because each single quote disorientate markup parser. Except this one, expression evaluated practically the same way as regular C# expression.
That's what I was getting at.
1

Try changing it to this:

<asp:Button ID="AddCartButton" runat="server" Text="Add To Cart" onClick="AddCartButton_Click" OnClientClick='<%# "AddItem('" + Eval("Name") + "', '" + Eval("Price") + "')"' />

or this also might work

<asp:Button ID="AddCartButton" runat="server" Text="Add To Cart" onClick="AddCartButton_Click" OnClientClick="AddItem('<%# Eval(&quot;Name&quot;) %>', '<%# Eval(&quot;Price&quot;) %>')" />

using quotes inside a server control attributes upsets the compilation process as it can't figure out where the attribute ends. You can either use apostrophes (1st example) or escape the quotes (2nd example)

1 Comment

The first solution still gives me a server tag error (I'm assuming there was a mistake at the end and changed it to )"%>' ) The second one doesn't work either, it passes <%# Eval("Name")%> as a parameter :/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.