How to refresh a label in a GridView?

I have created a wall with nested comments where users can comment on posts. The issue I'm facing is that whenever someone clicks on the thumbs up button, the entire page reloads. What I want is for only the label displaying the number of likes to be updated without refreshing the whole page. How can I achieve this? Below is my attempted solution which is not working as expected:

<asp:ImageButton ID="lnklike" runat="server" ImageUrl="~/Images/thumbsup.png" height="20px" Width="20px" CommandName="like" CommandArgument='<%# Eval("ScrapId")%>'/> &nbsp;
<asp:UpdatePanel ID="UpdatePanel1" runat="Server">
    <Triggers>
        <asp:AsyncPostBackTrigger controlid="lnklike" eventname="click"  />
    </Triggers>
    <ContentTemplate>  <asp:Label ID="Label1" runat="server" Text='<%# Controls_GetUserScraps.abc((int)Eval("ScrapId")) %>' />

protected void GridViewRowCommand(Object sender, GridViewCommandEventArgs e)
{

    var scrapId = Int32.Parse(e.CommandArgument.ToString());

    switch (e.CommandName)
    {
        case "like":

            string chklike = "select likestatus from tbl_like where fromid='" + Session["UserId"] + "' and scrapid='" + scrapId + "'";
            int a = dbo.GetLikesMethod(chklike);
            string chkthumbsdown = "select thumbsdownstatus from tbl_like where fromid='" + Session["UserId"] + "' and scrapid='" + scrapId + "'";
            int b = dbo.GetLikesMethod(chkthumbsdown);

            if (a == 0 && b == 0)
            {
                string sendlike = "insert into tbl_like (ScrapId,FromId,LikeStatus) values('" + scrapId + "','" + Session["UserId"] + "',1)";
                dbo.insert(sendlike);
                //abc(scrapId);
                GetUserScraps(int.Parse(Request.QueryString["Id"].ToString()));
            }
            else if (a != 0)
            {

                Response.Write("already liked");
            }
            else if (b != 0)
            {
                Response.Write("you can not like something you already downvoted!");
            }

            break;
    }
}

Method to get number of thumbs up /likes:

public static int abc(int scrpid)
{    
     string getlikes = "select COUNT(*) from tbl_like inner join Scrap on tbl_like.scrapid=Scrap.Id where tbl_like.likestatus=1 and tbl_like.scrapid='" + scrpid + "'";

     dboperation dbo = new dboperation();
     int a = dbo.GetLikesMethod(getlikes);

     return a;
}

public void GetUserScraps(int Id)
{
    string getUserScraps = "SELECT u.Id as UserId,u.firstname,u.ImageName,s.FromId,s.ToId,s.Message,s.SendDate,s.ID as ScrapId FROM [tbl_user] as u, Scrap as s WHERE u.Id=s.FromId AND s.ToId='" + Request.QueryString["Id"].ToString() + "'";
    //string getlikes = "select COUNT(*) from tbl_like inner join Scrap on tbl_like.scrapid=Scrap.Id where tbl_like.likestatus=1 and tbl_like.scrapid='"+<%#DataBinder.Eval(Container.DataItem,"ScrapId")%>+"'";
    //  <%#DataBinder.Eval(Container.DataItem,"ScrapId")%>

    dt = dbClass.ConnectDataBaseReturnDT(getUserScraps);
    if (dt.Rows.Count > 0)
    {
        GridViewUserScraps.DataSource = dt;
        GridViewUserScraps.DataBind();
    }
}

Answer №1

To enhance the grid functionality, you can incorporate a hyperlink by following this format:

<asp:TemplateField ItemStyle-Wrap="false" ItemStyle-Width="35px">
    <ItemTemplate>
       <a href="javascript:void(0);" onclick="Link to your javascript method/ajax method">
                                         </a>
    </ItemTemplate>
    <ItemStyle Wrap="False"></ItemStyle>
</asp:TemplateField>

Subsequently, utilize a jQuery ajax call similar to this example

Incorporate the returned count in JSON format and update the designated label

Ajax Call

function UpdateLikeStatus(imageID, labelid)
{
      $.ajax({
                type: 'POST',
                contentType: "application/json; charset=utf-8",
                url: 'Services/MiscService.asmx/UpdateLikeStatus',
                data: "{'imageid':'" + imageID + "'}",
                dataType: "json",
                success: function (data) {
                    //The specified label will display the new count.

                    $('#labelid').html(data.d);

                }
            });
}

Here is the Webservice call that could also be utilized within a WCF service. Refer to THIS LINK for guidance on implementing an AJAX webservice

[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string UpdateLikeStatus(string imageid)
{
   string returnedData = "";         
   //Execute a stored procedure to update status
   returnedData = Storedprocedurecall.UpdateLikeStatus(imageid); //Updates status and returns count 
     //Return the updated count.
   return returnedData;  

}

Trigger the like status update event by clicking on the image or relevant element.

<img src="" id="genericimage" border="0" onclick="UpdateLikeStatus('<%#Eval("imageid") %>', this);" />

imageid = identifier of the image to update the like status

If there are any clarifications needed, feel free to reach out.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can a session be prolonged by an ajax request triggered by a timer?

In my Asp.Net MVC application, I am looking to dynamically hide the cart and certain buttons when a user's session expires. I stumbled upon a solution that involves calling a function on a timer in ASP.NET MVC. Here is the reference link: How to call ...

Differences between searching for elements using `find` and `querySelector

When working with AngularJS, I encounter an error when trying to use querySelector. angular.element(angular.element(e).querySelector('.open')).removeClass('open'); However, if I switch to using: angular.element(angular.element(e).fin ...

Timeout while databinding GridView

Within my ASP.NET page, I have implemented a process that involves calling a stored procedure using SqlDataSource on Page_Load and then binding the data to a GridView. Here is an example of what I am doing: string connectionString = BLTutela.BLclsDatabase ...

Is it possible to set a value for a jQuery function after the function has

I am a beginner when it comes to javascript & jQuery. I am currently working on a feature for my website where users can display badges they have earned on their own site by simply copying and pasting a bit of code that I provide. Although the javascript p ...

Having difficulty retrieving the specific Laravel validation error message through AJAX

In my Laravel project, the error message I am encountering is: {message: "The given data was invalid.", errors: {oData: ["validation.required"]}} errors: {oData: ["validation.required"]} message: "The given data was invalid." I am not trying to display ...

Monitoring variables in AngularJS services

Hey, I'm having some trouble with this issue. I've searched everywhere for a solution, but couldn't find one, despite there being similar questions out there. Basically, I have a class and I only need one instance of it, so I created a serv ...

Executing the callback function

I am facing a situation where I have a Modelmenu nested within the parent component. It is responsible for opening a modal window upon click. Additionally, there is a child component in the same parent component that also needs to trigger the opening of a ...

An alternative approach to complex SQL updates in Rails 3

I am currently running an SQL query on 2 tables: affiliates_comisions.each do |aff| connection.update(" UPDATE comissions AS coms, conversions AS conve SET conve.active=0 WHERE coms.conversion_ty ...

Is there a way to pass multiple radio button values as a parameter?

I'm trying to figure out how to display an IList<string> array in radio buttons and pass prior month/s. Here's the code I currently have: In my view, I have this code that only displays the selected radio button value: foreach (var record ...

The Gusser Game does not refresh the page upon reaching Game Over

Hi there, I am a beginner in the world of JavaScript and currently working on developing a small guessing game app. However, I have encountered an issue where the page is not reloading after the game is over and the 'Play Again' button appears to ...

Assigning memory in C# for the + or ++ operator

Apologies if this question has been raised previously, as I have not been able to find a suitable keyword to search for it. If you have any suggestions for a keyword related to the issue below, please share them with me. The question at hand is: consider ...

Tips for automatically refreshing Node.js project while utilizing pm2

Working on Node.js with Express.js currently, whenever a modification is made in the router or app file, I find myself manually typing the command: pm2 reload id_project. Is there a way to set up pm2 for automatic project reloading upon file changes? ...

The randomness of a generated string is compromised if it is called multiple times

I'm having trouble generating a random string of words in a WebForms page using C# and ASP.NET. It works fine when called once, but when I call it multiple times in a row during a PostBack, it repeats the same random string each time. I suspect there ...

Encountering a 404 error when trying to retrieve parameters in Express JS

I am attempting to save a file by sending it as a JSON string through an ExpressJS POST request: app.post('/filewrite/', (req, res) => { const fs = require('fs'); console.log(req.body); fs.writeFile("./db/test.json", req.body, ...

I am interested in altering data across two different tables in MySQL

My production table looks like this: -------- --------- | Items | quantity | -------- --------- | A | 100 | -------------------- | B | 30 | -------------------- | A | 10 | -------------------- | C | 80. | --------- ...

Encountering an issue with the removal of slides when updating JSON data for angular-flexslider

Issue: Although my JSON object is updating, the slider does not update for all resorts as expected. Sometimes it fails to update when the JSON object changes. The resorts (image collections) that do not update are throwing an error stating "cannot read pr ...

The Battle of Extends and Intersection in Typescript

Typescript's concept of extension is akin to C++'s inheritance. Intersection in Typescript involves creating a new object with all the properties from the intersected classes. Why utilize intersection when extends keyword can already merge ...

Unable to refresh GroupBox in WinForm

I am struggling with refreshing a groupbox that contains Textboxes, Labels, Comboboxes, and other controls on button click. I have tried executing the following code but unfortunately, the refresh is not working as expected. try { //MySqlC ...

The data contract for type 'Newtonsoft.Json.Linq.JToken' is a recursive collection that is not supported. Please consider adjusting the collection definition

I am encountering an issue while trying to iterate through the server's response. The error message I keep receiving is: The data contract 'Type 'Newtonsoft.Json.Linq.JToken'' is a recursive collection, which is not supported. To ...

Using Spry Validate for form validation in conjunction with Ajax submission

I'm currently facing an issue where I want my form to validate before the ajax call is made, but I can't seem to figure out the correct coding for this process. When I separate them, I am able to either post using ajax without validation or with ...