-->

Tạo feedback với Star Rating & Comment Box trong ASP.NET Core MVC

Hiện nay, với các trang web bán hàng, hay là học trực tuyến,... thì việc tích hợp chức năng feedback là không thể thiếu. Chức năng này giúp tăng độ tin cậy với người dùng, và một phần dùng để marketing web lên.



Ở bài hướng dẫn này, mình sẽ hướng dẫn các bạn code chức năng star rating, và có cả khung comment với việc sử dụng HTML, CSS, JavaScript, jQuery, ASP.NET MVC and SQL Server.

Tiến hành

Bước 1: Trước tiên, bạn cần Thiết kế cơ sở dữ liệu (database) và tổ chức với 2 bảng sau:
  • Articles: (Bài viết) bảng này dùng để lưu trữ các bài viết.
  • ArticlesComments: bảng này lưu trữ các bình luận (comments) cùng với xếp hạng (star rating) cho một bài đăng cụ thể.

create database DbRatingSystem
go 
use DbRatingSystem
go
create table Articals
(
 Id  int identity(1,1) primary key,
 Title  nvarchar(50),
 [Description] nvarchar(255),
 Active  bit
)
create table ArticlesComments
(
 Id  int identity(1,1) primary key,
 Comment  nvarchar(500),
 CommentOn datetime,
 ArticalId int foreign key references Articals(Id),
 Rating  int
)

Trên là cơ sở dữ liệu mình thiết kế, hơi cẩu thả nên đã viết sai chính tả, mong các bạn thông cảm 😁.

Bước 2: Tạo project ASP.NET Core Web Application với tên là Rating.Demo

Bước 3: Chọn Web Application (Model - View - Controller).

Bước 4: Cài đặt các NuGet Package sau trong Rating.Demo:
  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.Relational
  • Microsoft.EntityFrameworkCore.SqlServer
  • Microsoft.EntityFrameworkCore.Tools

Bước 5: Thêm Connection Strings trong appsetting.json:


"ConnectionStrings": {
    "ConnectionString": "Server=CNPM-PC\\SQLEXPRESS;Database=DbRatingSystem;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
Bạn cần đổi tên Server trên thành tên Server của bạn trong SQL Server.

Bước 6: Vào Tools > NuGet Package Manager > Package Manager Console:



Sau đó nhập command như dưới:


Scaffold-DbContext "Server=CNPM-PC\SQLEXPRESS;Database= DbRatingSystem; user id= sa;password= 123;Trusted_Connection=True;MultipleActiveResultSets=true" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

Bước 7: Trong Startup.cs tìm đến phương thức ConfigureServices và thêm code sau bên trong phương thức:

services.AddDbContext<DbRatingSystemContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("ConnectionString")));

Bước 8: Từ folder Controllers, tạo mới Controller với MVC Controller with views, using Entity Framework:


Sau đó tạo mới ArticalsController.cs như dưới:


Sau đó, tượng tự tạo ArticlesCommentsController.cs 

Bước 9
: Ta vào Controllers/ArticalsController.cs và thay thế code của phương thức Details thành như sau:

// GET: Articles/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return BadRequest();
            }
            Articals article = _context.Articals.Find(id);
            if (article == null)
            {
                return BadRequest();
            }
            ViewBag.ArticleId = id.Value;

            var comments = _context.ArticlesComments.Where(d => d.ArticalId.Equals(id.Value)).ToList();
            ViewBag.Comments = comments;

            var ratings = _context.ArticlesComments.Where(d => d.ArticalId.Equals(id.Value)).ToList();
            if (ratings.Count() > 0)
            {
                var ratingSum = ratings.Sum(d => d.Rating.Value);
                ViewBag.RatingSum = ratingSum;
                var ratingCount = ratings.Count();
                ViewBag.RatingCount = ratingCount;
            }
            else
            {
                ViewBag.RatingSum = 0;
                ViewBag.RatingCount = 0;
            }

            return View(article);
        }

Bước 10: Trong Views/Articals/Details.cshtml thay thế tất cả code thành như sau:

@model Rating.Demo.Models.Articals

@{
    ViewData["Title"] = "Details";
}

@{
    ViewBag.Title = Model.Title;
    var comments = (IEnumerable<Rating.Demo.Models.ArticlesComments>)ViewBag.Comments;
    var ratingSum = ViewBag.RatingSum;
    var ratingCount = ViewBag.RatingCount;

    decimal rating = 0;
    if (ratingCount > 0)
    {
        rating = (ratingSum / ratingCount);
    }
    var totalRating = decimal.Parse(rating.ToString());
}

<h2>@Model.Title</h2>
<div>
    <span class="starFadeN" id="sRate1"></span><span class="starFadeN" id="sRate2"></span><span class="starFadeN" id="sRate3"></span><span class="starFadeN" id="sRate4"></span><span class="starFadeN" id="sRate5"></span>
</div>
<div>
    <dl class="dl-horizontal">

        <dt>
            @Html.DisplayNameFor(model => model.Description)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Description)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Active)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Active)
        </dd>

    </dl>
</div>
@foreach (var c in comments)
{
    <hr />
    <div class="row">
        <div class="col-md-3">
            <i>@c.CommentOn</i>
            <br />
            @for (var i = 1; i <= c.Rating; i++)
            {
                <span class="starGlowN"></span>
            }
            @for (var i = (c.Rating + 1); i <= 5; i++)
            {
                <span class="starFadeN"></span>
            }
        </div>
        <div class="col-md-9">
            @Html.Raw(c.Comment.Replace("\n", "<br />"))


        </div>
    </div>
}
<hr />
@Html.Partial("_CommentBox")

<script>
    function SCRate() {
        for (var i = 1; i <= @totalRating; i++) {
            $("#sRate" + i).attr('class', 'starGlowN');
        }
    }
    $(function(){
        SCRate();
    });
</script>
<div>
    <a asp-action="Edit" asp-route-id="@Model.Id">Edit</a> |
    <a asp-action="Index">Back to List</a>
</div>

Bước 11: Bổ sung css trong wwwroot > css > site.css như sau (thêm vào dưới cùng):

.commentBox {
    background-color: #efefef;
    padding: 10px;
    border-radius: 10px;
}

.starFade {
    background-image: url('https://i.imgur.com/l1v62LE.gif');
    min-width: 30px;
    min-height: 30px;
    display: inline-block;
    cursor: pointer;
}

.starFadeN {
    background-image: url('https://i.imgur.com/l1v62LE.gif');
    min-width: 30px;
    min-height: 30px;
    display: inline-block;
}

.starGlow {
    background-image: url('https://i.imgur.com/hHU12Q5.gif');
    min-width: 30px;
    min-height: 30px;
    display: inline-block;
    cursor: pointer;
}

.starGlowN {
    background-image: url('https://i.imgur.com/hHU12Q5.gif');
    min-width: 30px;
    min-height: 30px;
    display: inline-block;
}

Bước 12: Trong Views/Shared → add View mới tên là _CommentBox.cshtml và thêm code sau:

<dl class="dl-horizontal">
    <dt>
        Comment
    </dt>

    <dd>
        <div class="commentBox">
            @using (Html.BeginForm("Create", "ArticlesComments", FormMethod.Post, new { onsubmit = "return SubmitComment()" }))
            {
                @Html.AntiForgeryToken()
                <div class="form-horizontal">
                    <div class="form-group">
                        <label class="col-md-4 control-label">
                            Your rating <span style="font-weight:normal;">(1 start is bad, 5 star is good)</span>
                        </label>
                        <div class="col-md-7">
                            <div onmouseout="CRateSelected()">
                                <span class="starFade" id="Rate1" onclick="CRate(1)" onmouseover="CRateOver(1)" onmouseout="CRateOut(1)"></span><span class="starFade" id="Rate2" onclick="CRate(2)" onmouseover="CRateOver(2)" onmouseout="CRateOut(2)"></span><span class="starFade" id="Rate3" onclick="CRate(3)" onmouseover="CRateOver(3)" onmouseout="CRateOut(3)"></span><span class="starFade" id="Rate4" onclick="CRate(4)" onmouseover="CRateOver(4)" onmouseout="CRateOut(4)"></span><span class="starFade" id="Rate5" onclick="CRate(5)" onmouseover="CRateOver(5)" onmouseout="CRateOut(5)"></span>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-md-12">
                            <textarea name="Comment" id="Comment" required rows="5" style="width:100%;" class="form-control"></textarea>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-md-12">
                            <input type="hidden" name="ArticleId" value="@ViewBag.ArticleId" />
                            <input type="hidden" name="Rating" id="Rating" value="0" />
                            <input type="submit" id="btnRegister" name="btnRegister" value="Submit Comment" class="btn btn-warning" />
                        </div>
                    </div>
                </div>
            }
        </div>
    </dd>

</dl>
<script>
    function SubmitComment() {
        if ($("#Rating").val() == "0") {
            alert("Please rate this service provider.");
            return false;
        }
        else {
            return true;
        }
    }

    function CRate(r) {
        $("#Rating").val(r);
        for (var i = 1; i <= r; i++) {
            $("#Rate" + i).attr('class', 'starGlow');
        }
        // unselect remaining
        for (var i = r + 1; i <= 5; i++) {
            $("#Rate" + i).attr('class', 'starFade');
        }
    }

    function CRateOver(r) {
        for (var i = 1; i <= r; i++) {
            $("#Rate" + i).attr('class', 'starGlow');
        }
    }

    function CRateOut(r) {
        for (var i = 1; i <= r; i++) {
            $("#Rate" + i).attr('class', 'starFade');
        }
    }

    function CRateSelected() {
        var setRating = $("#Rating").val();
        for (var i = 1; i <= setRating; i++) {
            $("#Rate" + i).attr('class', 'starGlow');
        }
    }
</script>

Và thế là xong, hãy chạy lên và trải nghiệm nhé!

Để vào rating, bạn nhấn vào phần details của bài viết muốn rating.

Sau đó thực hiện rating và comment.


Khi nhấn vào Submit Comment sẽ chuyển sang trang quản lý các comments.

Lời kết

Đây là bài hướng dẫn, một phần nào giúp bạn hiểu hơn cách code chức năng feedback.

Mọi vấn đề thắc mắc hay gặp lỗi hãy comment dưới để cùng giải đáp.

Đây là cấu trúc của project trên để bạn tham khảo:


Mong bài viết có ích với bạn, chúc các bạn thành công.

By Hiếu Quốc

Có lẽ bạn thích?

19 comments

  1. Replies
    1. Đã đặt, bác đặt lại giúp mình nhé

      Delete
  2. Liên kết không anh zai
    Trần Thắng IT
    Tranthangit.tk

    ReplyDelete
    Replies
    1. Mình không nhận domain .tk nha bạn, bạn quay lại sau nhé

      Delete
  3. thay backlink togiapit đi e vs bro ơi
    thay thành :
    name :Lập Trình 5S
    url : https://www.laptrinh5s.net
    mô tả : Blog chia sẽ thủ thuật , kiến thức hay

    ReplyDelete
  4. Bác viết em khó điều chỉnh trang của em quá. Trang của em đang bị lỗi comment đây
    https://scgroup.com.vn/

    ReplyDelete

Post a Comment