ASP.NET Core 101 - Introducing Blazor: Interactivity(相互作用) [12 of 13]
We had made a star ratings system,addRatings that we added to our products service. We've got a modal pop-up(弹出窗口; 弹出式广告;) dialog right now,which is looking pretty sweet.
Then at the bottom, we've decided that we want some stars;a row of n number of stars,When you click on them,you can rate the product, and we're going to do that all in our Razor components. So it's self-contained.
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
we cheated a little bit and added in a Font Awesome class which contains some star images that we're going to use.
So right now we have SelectProduct,and what we need to do is we need to figure out what the current rating is,because our products service has the concept of rating.
@code { int currentRating = 0; int voteCount = 0; string voteLabel; void GetCurrentRating() { if(selectedProduct.Ratings == null) { currentRating = 0; voteCount = 0; } else { voteCount = selectedProduct.Ratings.Count(); voteLabel = voteCount > 1 ? "Votes" : "Vote"; currentRating = selectedProduct.Ratings.Sum() / voteCount; } System.Console.WriteLine($"Current rating for {selectedProduct.Id}: {currentRating}"); } void SubmitRating(int rating) { System.Console.WriteLine($"Rating received for {selectedProduct.Id}: {rating}"); ProductService.AddRating(selectedProductId, rating); SelectProduct(selectedProductId); } }
if the one that we're currently iterating on is smaller than the current rating,because we're going to have the stars change color whether this charge has been checked or not.So at onclick,that turns purple(紫色的; 华丽的文辞;) because Blazor and Razor components do that, and then we'll say E,E is event, Rocketship,submit rating, current star.
<div class="modal-footer"> @if(voteCount == 0) { <span>Be the first to vote!</span> } else { <span>@voteCount @voteLabel</span> } @for(int i=1; i<6; i++) { var currentStar = i; if(i<=currentRating) { <span class="fa fa-star checked" @onclick="(e => SubmitRating(currentStar))"></span> } else { <span class="fa fa-star" @onclick="(e => SubmitRating(currentStar))"></span> } } </div>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步