lundi 29 juin 2015

ASP.NET MVC Ajax will only update first in list

I have a list of Posts in my index page, where you can vote up and down on each one. My problem is that I can only vote on the first one in the list.

My JS:

<script type="text/javascript">
    $(document).ready(function () {
        function voteAjax(pid, vurl, value) {
            // Show a loading gif or something
            // $(".loading").show(); .hide();
            $.ajax({
                url: vurl,
                type: "GET",
                data: { vote: value, id: pid },
                success: function (data) {
                    if (data.success) {
                        // All went well, say thanks
                        $('#vote-display').html(data.displayValue);
                    } else {
                        // show ex error
                    }
                },
                error: function (err) {
                    // the call thrown an error
                },
                complete: function () {
                    // Hide loading gif
                }
            });
        }
        $('#vote-up').click(function () {
            var pid = $(this).attr("data-pid");
            var value = 1;
            var vurl = '@Url.Action("VotePost", "Services")';

            $.ajax({
                url: vurl,
                type: "GET",
                data: { vote: value, id: pid },
                success: function (data) {
                    if (data.success) {
                        // All went well, say thanks
                        $('#vote-display').html(data.displayValue);
                    } else {
                        // show ex error
                    }
                },
                error: function (err) {
                    // the call thrown an error
                },
                complete: function () {
                    // Hide loading gif
                }
            });
        });
    });
</script>

and my view where I display the posts in a list:

@foreach (var post in Model.Posts)
{
    <div class="row">
        <div class="col-md-1 vote-i">
            <a id="vote-up" data-pid="@post.PostID" class="glyphicon glyphicon-chevron-up vote-up"></a><br />
            <span id="vote-display">@Html.DisplayFor(modelPost => post.Vote.Value)</span><br/>
            <a id="vote-down" data-pid="@post.PostID" class="glyphicon glyphicon-chevron-down vote-down"></a><br/>
        </div>
    </div>
}

I suspect there is something going on when I get the postID and that Im only able to get the first one for some reason, but I can't figure it out.

Aucun commentaire:

Enregistrer un commentaire