简体   繁体   中英

Add a tag using HtmlGenericControl

I want to add 'a' tag with onserverclick attribute

I'm using the following code.But onserverclick event not firing(Not working)

onserverclick:

protected void Pagination_Click(object sender, EventArgs e)
{

}

My C# Code:

HtmlGenericControl li = new HtmlGenericControl("li");
olpage.Controls.Add(li);


HtmlGenericControl a = new HtmlGenericControl("a");
a.Attributes.Add("ID", i.ToString());
a.Attributes.Add("onserverclick", "Pagination_Click");
a.InnerHtml = i.ToString();
li.Controls.Add(a);

HTML Code:

<%@ Master Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true"CodeFile="Products.master.cs" Inherits="Productmaster"%>...
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">...
    <div class="pages">
         <ol id="olpage" runat="server">

         </ol>
    </div>...

Change your C# code to use a LinkButton instead of a HTMLGenericControl and instead of setting an attribute of onserverclick set it with Click +=

LinkButton a = new LinkButton();
a.Attributes.Add("ID", i.ToString()); 
a.Click += Pagination_Click;
a.Text = i.ToString();
li.Controls.Add(a);

The HTMLGenericControl just renders as

<a id="id" onserverclick="Pagination_Click">id</a>

And the browser doesn't know what to do with the onserverclick attribute as it's not valid HTML. Using the LinkButton renders as

<a id="id" href="javascript:__doPostBack('ctl00$MainContent$ctl01','')">id</a>

Which actually causes it to post back

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM