Sunday, 27 July 2014

How to Implement 5 star rating system in ASP.NET inside Gridview.


INTRODUCTION
In this post, I am explain how to Implement 5 star rating system in ASP.NET inside Gridview. 
STEPS :
STEP - 1 : CREATE NEW PROJECT.
Go to File > New > Project > Select asp.net web forms application > Entry Application Name > Click OK.
STEP-2: ADD A DATABASE.
Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.
STEP-3: CREATE 2 TABLE FOR SAVE/ FETCH DATA.
Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok. 
In this example, I have used two tables as below 
Table1






Table2



STEP-4: ADD Linq To Sql.
Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select Linq To Sql Class 
STEP-5: ADD A CLASS.

Right Click on Solution Explorer > Add > Class > Enter Class Name > Add.
Here is the class. 

public class ASPRatingApp
{
       public ASPRatingApp()
       {
              //
              // TODO: Add constructor logic here
              //
       }
    public int? ArticleID { get; set; }
    public string ArticleTitle { get; set; }
    public int? Score { get; set; }
}

STEP-6: ADD A WEBPAGE AND DESIGN FOR SHOW/SAVE RATING FROM/TO DATABASE.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select web form/ web form using master page under Web > Enter page name > Add.

Designer Code


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="script/jquery-1.7.1.js"></script>
<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        $(".rating-star-block .star").mouseleave(function () {
            $("#" + $(this).parent().attr('id') + " .star").each(function () {
                $(this).addClass("outline");
                $(this).removeClass("filled");
            });
        });
        $(".rating-star-block .star").mouseenter(function () {
            var hoverVal = $(this).attr('rating');
            $(this).prevUntil().addClass("filled");
            $(this).addClass("filled");
            $("#RAT").html(hoverVal);
        });
        $(".rating-star-block .star").click(function () {

            var v = $(this).attr('rating');
            var newScore = 0;
            var updateP = "#" + $(this).parent().attr('id') + ' .CurrentScore';
            var artID = $("#" + $(this).parent().attr('id') + ' .articleID').val();

            $("#" + $(this).parent().attr('id') + " .star").hide();
            $("#" + $(this).parent().attr('id') + " .yourScore").html("Your Score is : &nbsp;<b style='color:#ff9900; font-size:15px'>" + v + "</b>");
            $.ajax({
                type: "POST",
                url: "Default.aspx/SaveRating",
                data: "{articleID: '" + artID + "',rate: '" + v + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    setNewScore(updateP, data.d);
                },
                error: function (data) {
                    alert(data.d);
                }
            });
        });
    });
    function setNewScore(container, data) {
        $(container).html(data);
        $("#myElem").show('1000').delay(2000).queue(function (n) {
            $(this).hide(); n();
        });
    }
</script>
</head>
<body>
    <form id="form1" runat="server">
     <style type="text/css">
    .rating-star-block .star.outline {
        background: url("images/star-empty-lg.jpg") no-repeat scroll 0 0 rgba(0, 0, 0, 0);
    }
    .rating-star-block .star.filled {
        background: url("images/star-fill-lg.jpg") no-repeat scroll 0 0 rgba(0, 0, 0, 0);
    }
    .rating-star-block .star {
        color:rgba(0,0,0,0);
        display : inline-block;
        height:24px;
        overflow:hidden;
        text-indent:-999em;
        width:24px;
    }
    a {
        color:#005782;
        text-decoration:none;
    }
</style>
<h3>Rating in ASP.NET</h3>
<div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" CellPadding="5">
        <Columns>
            <asp:BoundField HeaderText="Article ID" DataField="ArticleID" />
            <asp:BoundField HeaderText="Article Title" DataField="ArticleTitle" />
            <asp:TemplateField>
                <ItemTemplate>
                    <div class="rating-star-block" id='div_<%#Container.DataItemIndex %>'>
                        <input type="hidden" class="articleID" value='<%#Eval("ArticleID") %>' />
                        Current Score :<span class="CurrentScore"><%#Eval("Score") %></span><br /><div class="yourScore">Your Score : </div>
                        <a class="star outline" href="#" rating="1" title="vote 1"> vote 1</a>
                        <a class="star outline" href="#" rating="2" title="vote 2"> vote 2</a>
                        <a class="star outline" href="#" rating="3" title="vote 3"> vote 3</a>
                        <a class="star outline" href="#" rating="4" title="vote 4"> vote 4</a>
                        <a class="star outline" href="#" rating="5" title="vote 5"> vote 5</a>
                    </div>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    <div id="myElem" style="position:absolute; top:10px; left:50%; display:none; background-color:yellow; padding:5px; border:1px solid red">
        Thank you for your rating!
    </div>
</div>
    </form>
</body>
</html>



Code Behind


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Entity;
using System.Data.EntityClient;
using System.Web.Services;
using System.Web.Script.Services;

public partial class _Default : System.Web.UI.Page
{
   
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            PopulateArticle();
    }
    private void PopulateArticle()
    {
        using (gangwarDataContext dc = new gangwarDataContext())
        {
            var v = (from a in dc.Articles
                     join b in dc.Scoretbs on a.ArticleID equals b.ArticleID into bb
                     from b in bb.DefaultIfEmpty()
                     group new { a, b } by new { a.ArticleID, a.Articletitle } into AA
                     select new
                     {
                         AA.Key.ArticleID,
                         AA.Key.Articletitle,
                         Score = AA.Sum(a => a.b.Score) == null ? 0 : AA.Sum(a => a.b.Score),
                         Count = AA.Count()
                     });
            List<ASPRatingApp> AWS = new List<ASPRatingApp>();
            foreach (var i in v)
            {
                AWS.Add(new ASPRatingApp
                {
                    ArticleID = i.ArticleID,
                    ArticleTitle = i.Articletitle,
                    Score = i.Score / i.Count
                });
                GridView1.DataSource = AWS;
                GridView1.DataBind();
            }
        }
    }
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static int SaveRating(int articleID, int rate)
    {
        int result = 0;
        using (gangwarDataContext dc = new gangwarDataContext())
        {
            dc.Scoretbs.InsertOnSubmit(new Scoretb
            {
                ArticleID = articleID,
                ScoreID = 0,
                Score = rate,
                Createdate = DateTime.Now.ToShortDateString()
            });
            dc.SubmitChanges();

            var newScore = (from a in dc.Scoretbs
                            where a.ArticleID.Equals(articleID)
                            group a by a.ArticleID into aa
                            select new
                            {
                                Score = aa.Sum(a => a.Score) / aa.Count()
                            }).FirstOrDefault();
            result = newScore.Score.Value;
        }
        return result;
    }
   
}



Tuesday, 22 July 2014

An alert if the user navigates from one page to other if there are any unsaved changes in asp.net

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <style type="text/css">
        body
        {
            font-family: Arial;
            font-size: 10pt;
        }
        table
        {
            border: 1px solid #ccc;
        }
        table th
        {
            background-color: #F7F7F7;
            color: #333;
            font-weight: bold;
        }
        table th, table td
        {
            padding: 5px;
            border-color: #ccc;
        }
    </style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("input[type=text], select, textarea").bind("keyup, change", function () {
                $(this).attr("rel", "edited");
            });
            $(window).on('beforeunload', function () {
                if ($("[rel='edited']").length > 0) {
                    return "There are some unsaved changes on the page. Do you still want to leave the page?";
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1">
    <table border="0" cellpadding="0" cellspacing="0">
        <tr>
            <td>
                Name:
            </td>
            <td>
                <input type="text" id="txtName" />
            </td>
        </tr>
        <tr>
            <td>
                Address:
            </td>
            <td>
                <textarea id="txtAddress" rows="3" cols="10"></textarea>
            </td>
        </tr>
        <tr>
            <td>
                Gender:
            </td>
            <td>
                <select>
                    <option value="">Please select</option>
                    <option value="M">Male</option>
                    <option value="F">Female</option>
                </select>
            </td>
        </tr>
        <tr>
            <td>
            </td>
            <td>
                <input type="submit" id="btnSubmit" value="Submit" />
                <a href = "Default.htm">Cancel</a>
            </td>
        </tr>
    </table>
    </form>
</body>
</html>