1

How to pass an ASP.NET model's parameter to the ng-click method?

@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            <button class="btn btn-default" ng-click="addToBasket()"></button>
        </td>
    </tr>
}

I want to pass item.Id to the addToBasket method set by ng-click attribute.

Is there an easy way to do it?

1 Answer 1

2
<button class="btn btn-default" ng-click="addToBasket(@( item.Id ))"></button>

Razor's special @ character is (generally) interpreted regardless of location or surrounding HTML syntax (which is a problem if you ever want to embed a static e-mail address in Razor...)

To escape the @ (such as for putting an e-mail address) just put it twice:

<input type="email" value="foo@@bar.com" />
Sign up to request clarification or add additional context in comments.

2 Comments

And why do you have brackets around item.Id? I thought that they're not required
@FrozenHeart Correct, they are not required, but I personally prefer to use parentheses to make it clearer - especially as I'm still a fan of the ASPX <%= %> syntax.

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.