简体   繁体   中英

ASP.NET: add postback to anchor

In my javascript file, I got an ajax to get all list and iterate these data and append <a id='userID' class='btn'>Assign ID<> to my list.

So, how do a add postback to these anchor and redirect it inside my method in the server. Below is my code but didn't work. When I click the achor button, it just redirect/refresh to the same page without doing any changes and didn't show the text.

<a id='uniqueID' class='btn assignID' href='javascript:void(0);' onclick='javascript:__doPostBack('uniqueID','')'>Assign ID</a>

protected void Action_assignID(object sender, EventArgs e)
{
  // assign ID action
  Response.Write("Pass");
}

You should be changed your button to:

<a id='uniqueID' class='btn assignID' href='javascript:void(0);' onclick="javascript:__doPostBack('uniqueID','Assign ID')">Assign ID</a>

And it's a good idea to implement the IPostBackEventHandler interface in your codebehind as below:

public partial class WebForm : Page, IPostBackEventHandler
{

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {

            }
        }

        public void RaisePostBackEvent(string eventArgument)
        {
             // do somethings at here
        }
}

Hope this help!

The __doPostBack method really doesn't do anything special except, well... perform a POST operation back to the same page with two specific form arguments.

The first parameter is the __EVENTTARGET and the second parameter is the __EVENTARGUMENT .

The magic all happens in ASP.Net where it automagically wires up your controls to event handlers, but since you are creating these entirely in JavaScript the server doesn't know that those controls exist.

However, you can manually grab these values and do something with them.

//Client Side JavaScript:
__doPostBack('my-event', '42');

//Code Behind
protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
    {
        var target = Request.Params["__EVENTTARGET"];
        var args = Request.Params["__EVENTARGUMENT"];

        Target.Text = target; // 'my-event'
        Argument.Text = args; // '42'
    }
}

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