简体   繁体   中英

Anchor control in Literal

using System;

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {

        public void Download(object obj, EventArgs e)
        {
            Response.Write("abc");
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            Literal1.Text = "<a id='anc' href ='#' runat='server' onserverclick='Download'>Click Me</a>";
            Response.Write(Literal1.Text);

        }
    }
}

 <div>
    <asp:Literal ID="Literal1" runat="server"></asp:Literal>
 </div>

I have the above code sniplet. I am trying to bind the anchor within the literal to a function in a following manner: onserverclick = "Download"

But the event is not firing. The requirement is that anchor is rendered through literal only.

Please help.

While your Literal1 control is a server-side control, setting the.Text value to represent a server control will not work.

Perhaps use the asp LinkButton control instead of a literal

so your.aspx page would have:

<asp:LinkButton ID="abc" runat="server" OnClick="Download" Text="Download" />

and your code behind.aspx.cs something like:

protected void Page_Load(object sender, EventArgs e)
{

}

protected void Download(object sender, EventArgs e)
{
    Response.Write("abc");
}

The attribute runat="server" is meaningless in the client-side code (which is what you're generating here). You may need to resort to calling a webservice.

We are using anchor tag outside literal. Then it works fine

If you do not wish to use a LinkButton, you could replace your Literal with the text which you are adding to it on Page_Load (not entirely sure why youre doing it this way anyway?).

And then run an AJAX web request to run the Download method.

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