Click here to Skip to main content
15,879,326 members
Articles / Web Development / HTML
Tip/Trick

Update WebGrid on Clients Without Postback using SignalR

Rate me:
Please Sign up or sign in to vote.
4.08/5 (9 votes)
3 Jul 2015CPOL2 min read 24.9K   3   12   9
Update WebGrid on clients without Postback using SignalR

Introduction

Till now, everyone has used a gridview to bind data on postbacks. Here, we make it dynamic using SignalR to update columns on each client where the gridview is displayed without postback or any server side operation.

Background

SiganlR and JQuery will make this possible. Before proceeding to the next step, I would suggest you refer to the scenario which was explained in the previous article.

Step 1: User clicks on Buy Now button to purchase a particular item:

Image 1

Step 2: After payment, user is again redirected back to this view with success message and Confirm Purchase button is visible.

Image 2

Step 3: After click of button Confirm Purchase, all the connected Clients are updated with the new quantity without reloading page or a postback.

Image 3

Using the Code

Following is the code for webgrid, here user clicks on Buy Now button to purchase a particular item, after payment, user is again redirected back to this view with Success message and then the quantity is reflected in the grid. Now this quantity which is to be updated is called by function from a hub class named ProjectHub. This function hits each client wherever the grid has the item, which is purchased. Hence, without refreshing or posting back to server, all the clients are updated.

JavaScript
// code for webgrid   

@grid.GetHtml(

      columns:

            grid.Columns(

            grid.Column("Preview", format: @<img src="@Url.Content
            (@System.Configuration.ConfigurationManager.AppSettings["ImagePath"] + @item.Preview)" />),
            grid.Column("ID","ID", format: @<label>@item.ProjID</label>),
            grid.Column("ProjectName", "ProjectName", 
            format: @<label id="lblProjName">@item.ProjectName</label>),
            grid.Column("Cost", "Cost", format: @<label>@item.Cost</label>),
            grid.Column("DOD", "DOD", format: @<label>@item.DOD</label>),
            grid.Column("Quantity", "Quantity", 
            format: @<label id="@item.ProjID" >@item.Quantity</label>),
            grid.Column(format:@<input type="button" 
            value="Buy Now" onclick="location.href='@Url.Action
            ("BuyNow", "Home", new { ProjID= @item.ProjID })'" />
             ))

View Onload Script

This script is responsible for connection with Hub Class and client function to update gridview column value.

JavaScript
@section scripts {
    <script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="~/signalr/hubs"></script>
    <!--SignalR script to update the chat page and send messages.-->
    <script>
        $(function () 
         {
            var control = document.getElementById('btnSuccess');
            control.style.visibility = "hidden";
            var someSession = '@ViewBag.message';
            if (someSession == "success")
            {
                var control = document.getElementById('btnSuccess');
                control.style.visibility = "visible";
            }
            var conn_hub = $.connection.projectsHub;
            conn_hub.client.UpdateGrid= function (ID, quant) 
            {
                var labelText = $('#' + ID + '').text().trim();
                var id = "#" + ID;
                $(id).text(quant);
             };
        });
}

Call to Hub Class Function

This code is useful to send data from a view to the Hub which will be responsible to update the clients connected to it.

JavaScript
@section scripts {
 $.connection.hub.start().done(function () 
{
            $('#btnSuccess').click(function () 
            {
                var control = document.getElementById('btnSuccess');
                control.style.visibility = "hidden";
                var ID='@ViewBag.ID';
                var conn_hub = $.connection.projectsHub;
                conn_hub.server.send(ID);
             });
});
}

Project Controller

Controller is responsible for authenticating the page and displaying the products list.

C#
public ActionResult Projects(string ID)
{
            if (User.Identity.IsAuthenticated)
            {
                EasySolutionEntities db = new EasySolutionEntities();
                if (Session["result"] == "success")
                {
                    var context = GlobalHost.ConnectionManager.GetHubContext<ProjectsHub>();
                    ViewBag.message = "success";
                    ViewBag.ID = ID;
                    ID = ID.Substring(0, 2);
                }
                Session["result"] = "";
                return View(db.fetch_projects(ID).ToList());
            }
            else
            {
                return Content("<script language='javascript' 
                type='text/javascript'>alert('Please Login for access');</script>");             
            }
}

Hub Class Code

Code for the Hub class which would update the clients connected with the new quantity count of products.

C#
public void Send(string ID)
{
EasySolutionEntities db = new EasySolutionEntities();

ObjectParameter quantity = new ObjectParameter("Quantity", typeof(int));

db.update_Quantity(ID,quantity);

string quant = quantity.Value.ToString();
Clients.All.UpdateGrid(ID, quant);
}

Download the code here.

Points of Interest

In this tip, we cover the following points:

  • Connection to Hub class
  • Updation of webgrid without postback

History

Refer to the following link to understand the scenario better:

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralCode not found Pin
stixoffire10-Sep-15 10:56
stixoffire10-Sep-15 10:56 
QuestionNice work Pin
dilshan ansari10-Jul-15 23:14
dilshan ansari10-Jul-15 23:14 
AnswerRe: Nice work Pin
Shashank S Chandel11-Jul-15 0:16
Shashank S Chandel11-Jul-15 0:16 
QuestionNice Article Pin
Santhakumar Munuswamy @ Chennai4-Jul-15 20:37
professionalSanthakumar Munuswamy @ Chennai4-Jul-15 20:37 
AnswerRe: Nice Article Pin
Shashank S Chandel4-Jul-15 21:03
Shashank S Chandel4-Jul-15 21:03 
GeneralMy vote of 5 Pin
vikiuser3-Jul-15 21:59
vikiuser3-Jul-15 21:59 
GeneralRe: My vote of 5 Pin
Shashank S Chandel4-Jul-15 5:49
Shashank S Chandel4-Jul-15 5:49 
Question404 on the code Pin
Dewey3-Jul-15 10:33
Dewey3-Jul-15 10:33 
AnswerRe: 404 on the code Pin
Shashank S Chandel4-Jul-15 21:00
Shashank S Chandel4-Jul-15 21:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.