0

ASP.NET Webform ListView ItemTemplate passing a value to a JavaScript function works correctly if the item_id is numeric. But I get this error if the item_id is alpha-numeric.

Uncaught ReferenceError: pf10001 is not defined
    at HTMLAnchorElement.onclick (Products.aspx:1182:163)
<a href="#" class="btn btn-sm btn-success" onclick='<%# "javascript:AddToCart(" + DataBinder.Eval(Container.DataItem, "item_id") + ");return false;" %>'>Add to Cart</a>

function AddToCart(item) {
    PageMethods.AddToCart(item, 0, onRequestComplete);
};

Have tried various hidden fields to pass the item_id value without success. But I'm wondering if there's a simple answer to this error.

2
  • You need to encapsulate the ID in quotes if it is alphanumeric. You don't need javascript: scheme in an onclick attribute, so it could just be onclick='<%# "AddToCart(\"" + DataBinder.Eval(Container.DataItem, "item_id") + "\");return false;" %>'>, but it's been a while since I touched a Webform, so this is a guess :). Commented May 26 at 17:57
  • Alternately, take a page out of Thymeleaf's approach and use data attributes Commented May 26 at 22:34

1 Answer 1

0

You’re rendering this in HTML:

<a onclick="AddToCart(pf10001);return false;">

(without quotes), so JS treats pf10001 as an undefined variable.

Solution

To actually emit quotes around the ID, you have to include them in the literal string you’re building this way:

<a href="#"
   class="btn btn-sm btn-success"
   onclick='<%# "AddToCart(\'" + Eval("item_id") + "\');return false;" %>'>
   Add to Cart
</a>
Sign up to request clarification or add additional context in comments.

Comments

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.