Asp.Net and gridView: how to create a link that initiates a method

Coreysan 1,736 Reputation points
2024-08-26T02:34:02.55+00:00

The asp.net GridView might not be able to do this, but I'm looking for a way to display a link

in a grid column, where the the user can click on the link which sends the value (a string) to a method,

and does work.

If not GridView, is there another grid, or maybe Javascript, or something else? I've tried HyperLink

and HyperLinkField, and they don't call a method.

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,907 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,504 questions
0 comments No comments
{count} votes

Accepted answer
  1. Lan Huang-MSFT 29,746 Reputation points Microsoft Vendor
    2024-08-26T07:46:05.64+00:00

    Hi @Coreysan,

    Based on your description, maybe you want to achieve something like the following?

    This function GetProfile is called during the data binding, not when the link is clicked. If you really want something to be called when the link is clicked, you need a LinkButton to generate a grid view command, and then handle that. However your current solution should work as well.

    <asp:TemplateField HeaderText="Hyperlink">
        <ItemTemplate>
            <asp:HyperLink ID="lblCreator" runat="server" NavigateUrl='<%# GetProfile(Eval("ItemName") as string) %>' Text='<%#Eval("ItemName") %>'></asp:HyperLink>
        </ItemTemplate>
    </asp:TemplateField>
    
     protected string GetProfile(string ItemName)
     {                     
      return "~/WebForm2.aspx?ItemName=" + ItemName;
         
     }
    

    User's image

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 66,226 Reputation points
    2024-08-26T02:42:03.18+00:00

    Links navigate to a new page. To send data from the client to the server you use JavaScript and Ajax to call server code.

    0 comments No comments

  2. SurferOnWww 3,031 Reputation points
    2024-08-27T03:13:16.7433333+00:00

    how to create a link that initiates a method

    You will be able to call static web method in the .aspx.cs. See "Calling Static Methods in an ASP.NET Web Page" section in the following Microsoft document:

    Exposing Web Services to Client Script

    I'm looking for a way to display a link in a grid column, where the the user can click on the link which sends the value (a string) to a method, and does work.

    Add the TemplateFiled to the GridView. Put the LinkButton control in the ItemTemplate of TemplateField.

    Add the static methods to the .aspx.cs

    Set javascript to the OnClientClick property of the LinkButton so that the static method is called on click.

    Disable the user friendly url if you use it. Otherwise the static method will not work.

    Shown below is a sample:

    .aspx.cs

    using System;
    using System.Web.Services;
    
    namespace WebForms1
    {
        public partial class GridView : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
    
            }
    
            [WebMethod]
            public static string MyWebMethod(int id)
            {
                return $"WebMethod called with id={id}";
            }
    
            protected string SetOnClientClick(int id)
            {
                return $"CallWebMthod({id}); return false;";
            }
        }
    }
    

    .aspx

    <%@ Page Language="C#" AutoEventWireup="true" 
        CodeBehind="GridView.aspx.cs" 
        Inherits="WebForms1.GridView" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title></title>
        <script src="Scripts/jquery-3.7.0.js"></script>
        <script type="text/javascript">
            function CallWebMthod(productId) {
                $.ajax({
                    type: "POST",
                    url: "GridView.aspx/MyWebMethod",
                    contentType: "application/json; charset=utf-8",
                    data: `{ "id": ${productId} }`
                }).done(response => {
                    $("#result").empty;
                    $("#result").text(response.d);
                });
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <asp:SqlDataSource ID="SqlDataSource1" 
                runat="server" 
                ConnectionString="<%$ ConnectionStrings:NORTHWINDConnectionString %>" 
                SelectCommand="SELECT TOP(10) [ProductID], [ProductName] FROM [Products]">
            </asp:SqlDataSource>
    
            <asp:GridView ID="GridView1" 
                runat="server" 
                AutoGenerateColumns="False" 
                DataKeyNames="ProductID" 
                DataSourceID="SqlDataSource1">
                <Columns>
                    <asp:BoundField DataField="ProductID" 
                        HeaderText="ProductID" 
                        InsertVisible="False" 
                        ReadOnly="True" 
                        SortExpression="ProductID" />
                    <asp:BoundField DataField="ProductName" 
                        HeaderText="ProductName" 
                        SortExpression="ProductName" />
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:LinkButton ID="LinkButton1" 
                                runat="server" 
                                OnClientClick='<%# SetOnClientClick((int)Eval("ProductID")) %>'>
                                LinkButton
                            </asp:LinkButton>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
    
            <div id="result"></div>
        </form>
    </body>
    </html>
    
    

    Result:

    enter image description here

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.