Jordan1993
Jordan1993

Reputation: 822

How to pass model property from Razor View to JavaScript function

I have the following in my view

@{
    foreach (var book in @Books)
    {
        <tbody>
            <tr>
                <th scope="row">@book.Title</th>
                <th scope="row">@book.Author</th>
                <th scope="row">
                    <button onclick="favouriteBook(@book.Id)">Favourite</button>
                </th>
            </tr>
        </tbody>
    }
}

And a JavaScript function in a separate file (Which is being correctly loaded as I have tested with a console.log:

function favouriteBook(id) {
    localStorage.setItem("bookId", id); 
    // Later to be a DB, just testing for now. 
}

However when this function is called by the user clicking on the button, I get an Uncaught SyntaxError: Invalid or unexpected token error. What is wrong here?

Upvotes: 1

Views: 1172

Answers (1)

Serge
Serge

Reputation: 43969

Change your button html

<button id="@book.Id" class="favoriteBookBtn" onClick="favouriteBook(this.id)">Favourite</button>

But much better way is to remove onClick="favouriteBook(this.id)" and use Unobtrusive JavaScript. It is the way of writing JavaScript language in which we properly separate Document Content and Script Content thus allowing us to make a clear distinction between them. This approach is useful in so many ways as it makes the code less error prone, easy to update and to debug.


@section Scripts {
<script>

$(document).ready(function () {
    $(".favoriteBookBtn").click(function (e) {
e.preventDefault();
         var id=this.id;       
...your code
     });
});

</script>
}

Upvotes: 1

Related Questions