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>
复制代码

 

posted @   FH1004322  阅读(134)  评论(0)    收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示