Reputation: 598
I have table with products, and I want to display in real-time votes amount for each product using SignalR. I don't know why $.connection.hub.start() inside jquery "each" method don't work properly. I tried put $('td').each function inside $.connection.hub.start(), but then strange things happens when debugging method in Hub :
<div class="products">
<table class="tableClass">
<tbody>
<tr>
@foreach (var item in Model.Products)
{
<td class="@item.Id">
<span class="productId" hidden="hidden">@item.Id</span>
<img src="~/Images/imageNotFound.png" style="max-width: 420px; max-height: 420px" />
<span>@item.Name</span>
@*@Html.ActionLink("Vote", "AddVote", new { productId = item.Id }, new { type = "button" })*@
<input type="button" class="voteBtn" title="Vote" value="Vote" itemid="@item.Id" />
<br />
<span class="votesAmount"></span>
</td>
}
</tr>
</tbody>
</table>
<span class="messageClass" style="color:red;"></span>
</div>
Hub:
public void VotesAmount(int productId, string className)
{
GetVotesAmountResponse response = VoteService.GetVotesAmount(new GetVotesAmountRequest() { ProductId = productId });
int votesAmount = 0;
if (response.Status == true)
{
votesAmount = response.Amount;
Clients.Caller.getVotesAmount(votesAmount, className);
}
else
{
Clients.Caller.getVotesAmount(votesAmount, className);
}
}
Script in view:
vote.client.getVotesAmount = function (votesAmount, className) {
$('td.'+className).find('span.votesAmount').text('VotesAmount: ' + votesAmount + ' ProductID:' + productId);
};
$('td').each(function () {
$.connection.hub.start().done(function () {
vote.server.votesAmount($(this).find('.productId').text(), $(this).attr('class'));
});
})
I tried this too (not working though):
$.connection.hub.start().done(function () {
$('td').each(function () {
vote.server.votesAmount($(this).find('.productId').text(), $(this).attr('class'));
});
});
Upvotes: 0
Views: 102
Reputation: 1547
The second option should work. Problem is with the product id in the callback method.
vote.client.getVotesAmount = function (votesAmount, className) {
$('td.'+className).find('span.votesAmount').text('VotesAmount: ' + votesAmount +
'ProductID:' + productId); };
productid variable is not available here inside this method. So I removed that and it worked. Better you can assign value or remove that.
Upvotes: 1