Sistemas web: C#/MVC – Avaliação por estrelas

Imagem mostra telas de computador

Sistemas web: C#/MVC – Avaliação por estrelas

Após receber uma solicitação para criar uma funcionalidade de avaliação por estrelas em um sistema web, notei que havia poucos exemplos em sites ou blogs, para sistemas web na linguagem c#.

Comecei a procurar em alguns sites estrangeiros e encontrei algumas sugestões. Adequei ao meu cenário, e hoje nesse post, demonstrarei como é possível realizar essa funcionalidade, a fim de atender essa demanda, e também de ajudar vocês que possuam uma necessidade semelhante.

Vamos lá?

No meu caso precisaria criar uma tela, com opção do usuário atribuir notas a 3 requisitos do prestador de serviços adquirido: preço, comunicação e qualidade. Tudo isso, através de ícones de estrelas, muito utilizado em aplicativos, mas não tão comum em plataforma web.

Usando uma estrutura MVC5, na linguagem C#. Temos como resultado:

1 – No meu projeto tenho 5 camadas, porém você poderá fazer isso apenas com uma.

Como início devemos criar uma model chamada Evaluation, com as propriedades que irei precisar:

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

namespace ViewModel

{

public class EvaluationViewModel

{

public UserViewModel User { get; set; }

public List<EvaluationViewModel> ListEvaluation = new List<EvaluationViewModel>();

public int TotalRows { get; set; }

public int PageSize { get; set; }

#region Properties

public int Id { get; set; }

public int IdUserLP { get; set; }

public int IdUserSP { get; set; }

public string LogisticName { get; set; }

public string ShipperName { get; set; }

public string QuoteNumber { get; set; }

public int IdOffer { get; set; }

public int? IdOfferLP { get; set; }

[Display(Name = “Profile”)]

public int IdProfile { get; set; }

[Display(Name = “Communication:”)]

public int? Communication { get; set; }

[Display(Name = “Reliability:”)]

public int? Reliability { get; set; }

[Display(Name = “Pricing:”)]

public int? Pricing { get; set; }

[Display(Name = “Insert your comment:”)]

public string Comment { get; set; }

#endregion

#region Properties Rel

#endregion

#region Filters

#endregion

}

}

2 – Iremos criar uma controller chamada Evaluation, com 2 actions Create:

public ActionResult Create(int? id = 0, int? IdOfferLP = 0)

{

List<EvaluationViewModel> ListModel = new List<EvaluationViewModel>();

ControlSession.Create<EvaluationViewModel>(ListModel);

var sessionList = ControlSession.ReadList<EvaluationViewModel>();

#region MyRegion

OffersViewModel modelOffer = new OffersViewModel();

modelOffer = this._serviceOffer.ReadOfferReceived(Convert.ToInt32(id), Convert.ToInt32(IdOfferLP));

EvaluationViewModel model = new EvaluationViewModel();

model.Id = modelOffer.Id;

model.IdOfferLP = modelOffer.IdOfferLP;

model.IdUserSP = Convert.ToInt32(modelOffer.IdUser);

model.IdUserLP = Convert.ToInt32(modelOffer.IdUserLogistic);

model.LogisticName = modelOffer.LogistcName;

model.LogisticName = modelOffer.ShipperName;

#endregion

return View(model);

}

[HttpPost]

public ActionResult Create(EvaluationViewModel model, string Comment)

{

var sessionList = ControlSession.ReadList<EvaluationViewModel>();

model.ListEvaluation = sessionList;

model.Comment = Comment;

this._serviceEvaluation.Create(model);

List<EvaluationViewModel> ListModel = new List<EvaluationViewModel>();

ControlSession.Create<EvaluationViewModel>(ListModel);

TempData[“msgSuccess”] = string.Format(“Thank you for your rating”)

return RedirectToAction(“Index”, “Home”);

}

Note que recuperarmos os valores armazenados na session.

Imagem mostra pessoa usando computador

3 – Vamos criar a view  e as partivalview, onde o usuário irá realizar a avaliação:

View:

@model ViewModel.EvaluationViewModel

@{

Layout = “~/Views/Shared/_Layout.cshtml”;

}

@{

ViewBag.Title = “Criar usuário”;

}

@if (Model.IdUserLP != 0)

{

<center><h3>RATE YOUR LOGISTICS PROVIDER: <b>@Model.LogisticName</b></h3></center>

}

else

{

<center><h3>RATE YOUR LOGISTICS PROVIDER: <b>@Model.ShipperName</b></h3></center>

}

<div class=”panel panel-primary” data-collapsed=”0″>

<div class=”panel-body”>

 

@using (Html.BeginForm(“Create”, “Evaluation”, FormMethod.Post, new { enctype = “multipart/form-data”, @class = “form-horizontal form-groups-bordered”, @role = “form” }))

{

@Html.AntiForgeryToken()

@Html.HiddenFor(model => model.Id)

@Html.HiddenFor(model => model.IdOfferLP)

@Html.HiddenFor(model => model.IdUserLP)

@Html.HiddenFor(model => model.IdUserSP)

<div class=”form-group”>

@Html.LabelFor(model => model.Pricing, htmlAttributes: new { @class = “col-sm-3 control-label” })

<div class=”col-sm-5″>

<div class=”tr”>

<div class=”td”>@Html.Partial(“_DefineNotePricePricing”, Model.Id.ToString())</div>

</div>

</div>

</div>

<div class=”form-group”>

@Html.LabelFor(model => model.Communication, htmlAttributes: new { @class = “col-sm-3 control-label” })

<div class=”col-sm-5″>

<div class=”tr”>

<div class=”td”>@Html.Partial(“_DefineNoteCommunication”, Model.Id.ToString())</div>

</div>

</div>

</div>

<div class=”form-group”>

@Html.LabelFor(model => model.Reliability, htmlAttributes: new { @class = “col-sm-3 control-label” })

<div class=”col-sm-5″>

<div class=”tr”>

<div class=”td”>@Html.Partial(“_DefineNoteReliability”, Model.Id.ToString())</div>

</div>

</div>

</div>

<div class=”form-group”>

@Html.LabelFor(model => model.Comment, htmlAttributes: new { @class = “col-sm-3 control-label” })

<div class=”col-sm-5″>

<textarea class=”form-control autogrow” name=”Comment” id=”Comment” rows=”8″></textarea>

</div>

</div>

<div class=”form-group text-center”>

<div class=”col-sm-11″>

<button type=”submit” class=”btn btn-green btn-icon”>Send Evaluation<i class=”entypo-check”></i></button>

<a href=”@Url.Action(“Details”, “Quotes”, new { Id = Model.Id, IdOfferLP = Model.IdOfferLP }) class=”btn btn-blue btn-icon”>See Quotes Details<i class=”entypo-info”></i></a>

</div>

</div>

}

</div>

</div>

<link rel=”stylesheet” href=”~/Content/custom/css/site.css” />

<script src=”~/Content/neon/assets/js/fileinput.js”></script>

<script src=”~/Content/neon/assets/js/jquery.validate.min.js”></script>

<script src=”~/Content/microsoft/jquery.validate.unobtrusive.min.js”></script>

PartialViews:

@model string

@{

var url = Request.Url.AbsolutePath;

}

<style type=”text/css”>

.ratingStar {

cursor: pointer;

}

</style>

@if (Request.Cookies[url] == null)

{

<div id=”ratingDivCom” class=”smallText”>

<img width=”30″ height=”30″ src=”/Content/custom/images/Star5.png” alt=”” class=”ratingStar” data-value=”1″ /><img width=”30″ height=”30″ src=”/Content/custom/images/Star5.png” alt=”” class=”ratingStar” data-value=”2″ /><img width=”30″ height=”30″ src=”/Content/custom/images/Star5.png” alt=”” class=”ratingStar” data-value=”3″ /><img width=”30″ height=”30″ src=”/Content/custom/images/Star5.png” alt=”” class=”ratingStar” data-value=”4″ /><img width=”30″ height=”30″ src=”/Content/custom/images/Star5.png” alt=”” class=”ratingStar” data-value=”5″ />

<label id=”lblResultCom”></label>

</div>

}

<script type=”text/javascript”>

var clickedFlag = false;

$(“.ratingStar”).mouseover(function () {

$(this).attr(“src”, “/Content/custom/images/Star1.png”).prevAll(“img.ratingStar”).attr(“src”, “/Content/custom/images/Star1.png”);

});

$(“.ratingStar, #radingDiv”).mouseout(function () {

$(this).attr(“src”, “/Content/custom/images/Star5.png”);

});

$(“#ratingDivCom”).mouseout(function () {

if (!clickedFlag)

{

$(“.ratingStar”).attr(“src”, “/Content/custom/images/Star5.png”);

}

});

$(“.ratingStar”).click(function () {

clickedFlag = true;

$(“.ratingStar”).unbind(“mouseout mouseover click”).css(“cursor”, “default”);

var url = “/Evaluation/DefineNoteCommunication?r=” + $(this).attr(“data-value”) + “&s=5&id=@Model&url=@url;

$.post(url, null, function (data) {             

//$(“#lblResultCom”).html(data);

});

});

$(“#lblResultCom”).ajaxStart(function () {

$(“#lblResultCom”).html(“Processing ….”);

});

$(“#lblResultCom”).ajaxError(function () {

$(“#lblResultCom”).html(“<br />Error occured.”);

});

</script>

@model string

@{

var url = Request.Url.AbsolutePath;

}

<style type=”text/css”>

.ratingStarPrice {

cursor: pointer;

}

</style>

@if (Request.Cookies[url] == null)

{

<div id=”ratingDivPrice” class=”smallText”>

<img width=”30″ height=”30″ src=”/Content/custom/images/Star5.png” alt=”” class=”ratingStarPrice” data-value=”1″ /><img width=”30″ height=”30″ src=”/Content/custom/images/Star5.png” alt=”” class=”ratingStarPrice” data-value=”2″ /><img width=”30″ height=”30″ src=”/Content/custom/images/Star5.png” alt=”” class=”ratingStarPrice” data-value=”3″ /><img width=”30″ height=”30″ src=”/Content/custom/images/Star5.png” alt=”” class=”ratingStarPrice” data-value=”4″ /><img width=”30″ height=”30″ src=”/Content/custom/images/Star5.png” alt=”” class=”ratingStarPrice” data-value=”5″ />

<label id=”lblResultPrice”></label>

</div>

}

<script type=”text/javascript”>

var clickedFlag = false;

$(“.ratingStarPrice”).mouseover(function () {

$(this).attr(“src”, “/Content/custom/images/Star1.png”).prevAll(“img.ratingStarPrice”).attr(“src”, “/Content/custom/images/Star1.png”);

});

$(“.ratingStarPrice, #radingDiv”).mouseout(function () {

$(this).attr(“src”, “/Content/custom/images/Star5.png”);

});

$(“#ratingDivPrice”).mouseout(function () {

if (!clickedFlag)

{

$(“.ratingStarPrice”).attr(“src”, “/Content/custom/images/Star5.png”);

}

});

$(“.ratingStarPrice”).click(function () {

clickedFlag = true;

$(“.ratingStarPrice”).unbind(“mouseout mouseover click”).css(“cursor”, “default”);

 

var url = “/Evaluation/DefineNotePricePricing?r=” + $(this).attr(“data-value”) + “&s=5&id=@Model&url=@url;

$.post(url, null, function (data) {

//$(“#lblResultPrice”).html(data);

});

});

$(“#lblResultPrice”).ajaxStart(function () {

$(“#lblResultPrice”).html(“Processing ….”);

});

$(“#lblResultPrice”).ajaxError(function () {

$(“#lblResultPrice”).html(“<br />Error occured.”);

});

</script>

Cada atributo de nota receberá sua particial view, e iremos alterar a imagem conforme o usuário passe o mouse, caso o usuário clique iremos chamar um método JSon, para armazenar esse valor na session, que foi recuperada no método acima.

public JsonResult DefineNoteCommunication(string r, string s, string id, string url)

{

EvaluationViewModel model = new EvaluationViewModel();

model.Communication = Convert.ToInt32(r);

model.ListEvaluation.Add(model);

if (ControlSession.ReadList<EvaluationViewModel>() != null)

{

ControlSession.ReadList<EvaluationViewModel>().Add(model);

}

else

{

ControlSession.Create<EvaluationViewModel>(model.ListEvaluation);

}

return Json(“<br />You rated “ + r + ” star(s), thanks !”);

}

public JsonResult DefineNotePricePricing(string r, string s, string id, string url)

{

EvaluationViewModel model = new EvaluationViewModel();

model.Pricing = Convert.ToInt32(r);

model.ListEvaluation.Add(model);

if (ControlSession.ReadList<EvaluationViewModel>() != null)

{

ControlSession.ReadList<EvaluationViewModel>().Add(model);

}

else

{

ControlSession.Create<EvaluationViewModel>(model.ListEvaluation);

}

return Json(“<br />You rated “ + r + ” star(s), thanks !”);

}

4 – Feito, isso vamos para o último passo, onde iremos recuperar os valores das sessões e gravar no banco:

var sessionList = ControlSession.ReadList<EvaluationViewModel>();

model.ListEvaluation = sessionList;

model.Comment = Comment;

this._serviceEvaluation.Create(model);

Note que recuperamos os valores das sessões e atribuíamos a uma lista.

Para recuperar os valores selecionados, faremos um foreach nessa lista e verificar se existe um valor:

Feito, isso iremos somar os 3 valores selecionados, e dividir por 3 para chegar a uma média.

if(model.ListEvaluation != null)

{

foreach (var item in model.ListEvaluation)

{

if(item.Pricing != 0 && item.Pricing != null)

{

NotePricing = item.Pricing;

NoteAll = NoteAll + Convert.ToInt32(NotePricing);

}

if (item.Communication != 0 && item.Communication != null)

{

NoteCommunication = item.Communication;

NoteAll = NoteAll + Convert.ToInt32(NoteCommunication);

}

if (item.Reliability != 0 && item.Reliability != null)

{

NoteRebiability = item.Reliability;

NoteAll = NoteAll + Convert.ToInt32(NoteRebiability);

}

NoteMedia = (NoteAll) / 3;

}                                                                               

Após isso basta gravar os dados no banco de dados.

5 – Para exibir isso depois, basta recuperarmos o valor da media do banco de dados, e definir quantas estrelas iremos exibir para aquele determinado usuário que foi avaliado.

@if (item.NoteMediaLP == 1)

{

<a style=”text-align:center; align-content:center” href=”@Url.Action(“Details”, “Evaluation”, new { LogisticName = item.NameLogistic, IdLogistic = item.IdUserLogistic, NoteMedia = item.NoteMediaLP,NoteMediaPricing = item.NoteMediaPricingLP,NoteMediaComm = item.NoteMediaCommunicationLP,NoteMediaReabili = item.NoteMediaReliabilityLP }) title=”See Details”><i class=”entypo-star” style=”color:gold”></i></a>

}

@if (item.NoteMediaLP == 2)

{

<a style=”text-align:center; align-content:center” href=”@Url.Action(“Details”, “Evaluation”, new { LogisticName = item.NameLogistic, IdLogistic = item.IdUserLogistic, NoteMedia = item.NoteMediaLP,NoteMediaPricing = item.NoteMediaPricingLP,NoteMediaComm = item.NoteMediaCommunicationLP,NoteMediaReabili = item.NoteMediaReliabilityLP }) title=”See Details”><i class=”entypo-star” style=”color:gold”></i></a>

<a style=”text-align:center; align-content:center” href=”@Url.Action(“Details”, “Evaluation”, new { LogisticName = item.NameLogistic, IdLogistic = item.IdUserLogistic, NoteMedia = item.NoteMediaLP,NoteMediaPricing = item.NoteMediaPricingLP,NoteMediaComm = item.NoteMediaCommunicationLP,NoteMediaReabili = item.NoteMediaReliabilityLP }) title=”See Details”><i class=”entypo-star” style=”color:gold”></i></a>

}

@if (item.NoteMediaLP == 3)

{

<a style=”text-align:center; align-content:center” href=”@Url.Action(“Details”, “Evaluation”, new { LogisticName = item.NameLogistic, IdLogistic = item.IdUserLogistic, NoteMedia = item.NoteMediaLP,NoteMediaPricing = item.NoteMediaPricingLP,NoteMediaComm = item.NoteMediaCommunicationLP,NoteMediaReabili = item.NoteMediaReliabilityLP }) title=”See Details”><i class=”entypo-star” style=”color:gold”></i></a>

<a style=”text-align:center; align-content:center” href=”@Url.Action(“Details”, “Evaluation”, new { LogisticName = item.NameLogistic, IdLogistic = item.IdUserLogistic, NoteMedia = item.NoteMediaLP,NoteMediaPricing = item.NoteMediaPricingLP,NoteMediaComm = item.NoteMediaCommunicationLP,NoteMediaReabili = item.NoteMediaReliabilityLP }) title=”See Details”><i class=”entypo-star” style=”color:gold”></i></a>

<a style=”text-align:center; align-content:center” href=”@Url.Action(“Details”, “Evaluation”, new { LogisticName = item.NameLogistic, IdLogistic = item.IdUserLogistic, NoteMedia = item.NoteMediaLP,NoteMediaPricing = item.NoteMediaPricingLP,NoteMediaComm = item.NoteMediaCommunicationLP,NoteMediaReabili = item.NoteMediaReliabilityLP }) title=”See Details”><i class=”entypo-star” style=”color:gold”></i></a>

}

 Espero ter ajudado de alguma forma. Acompanhe as próximas dicas da Luby.

Leave your thought here

Your email address will not be published. Required fields are marked *

Categorias