I was working on ASP.NET, had to open a confirm box in a UserControl, I achieved it after some searches on the web.I used ScriptManager.RegisterStartupScript because I had UpdatePanels.That is how I called the JS function from code behind
string privateChatUyeHesapAdi = BAL.Cari.Cari.GetCariHesapAdi(i);
string jsMethodForPrivateChat = "privatechatRequestConfirmation('" + privateChatUyeHesapAdi + "')";
ScriptManager.RegisterStartupScript(UpdtPnlOzelSohbetButton, UpdtPnlOzelSohbetButton.GetType(), "confirmprivatechatrequest", jsMethodForPrivateChat, true);
And this is the JS function
function privatechatRequestConfirmation(uyeHesapAdi) {
confirm(uyeHesapAdi + " wants to chat. ");
}
Afterwards, it turned out that I need to some stuff according to the return value of the confirmation, which is pretty normal but as a noob I couldn't guess it at the beginning, and I changed my JS function to this
function privatechatRequestConfirmation(uyeHesapAdi) {
var isConfirmed = confirm(uyeHesapAdi + " wants to chat ");
}
Now, I have the return value in isConfirmed variable.
What I need to do is basically click a button on the UserControl.
I said to myself "I did this before, it's easy.Just get the element with client id and call click().".Tried it like this
document.getElementById('<%= BttnKickMembersForPrivateChat.ClientID %>').click();
Well, I got that JavaScript error saying "click is not defined".Damn...
I tried not using ClienID or tried OnClick = true insted of click().None of them worked.
After some researches I ended up with __doPostBack() method, actually it is like this
__doPostBack(eventTarget, eventArgument)
So it takes a target control and a event argument, from
wiki.asp.net __doPostBack function I figured out that I can send my button name as eventTarget and OnClick as eventArgument I tried it like this
__doPostBack('BttnKickMembersForPrivateChat', 'OnClick');
Well, it didn't fire that button's onclick event then I tried
__doPostBack('BttnKickMembersForPrivateChat', 'BttnKickMembersForPrivateChat_Click');
BttnKickMembersForPrivateChat_Click is the name of onclick event on code-behind, but again it didn't fire.
Then I realized the 5th step of that link on wiki.asp.net
In the PageLoad method:
if (Request.Form["__EVENTTARGET"] == "Button2")
{
//fire event
Button2_Click(this, new EventArgs());
}
And I added that part in my Page_Load, well I saw that I obviously do not need the click event now, "just write a method Ateş, and call that" I said to myself and I did.
In my Page_Load method
if (Request.Form["__EVENTTARGET"] == "BttnKickMembersForPrivateChat")
{
method();//just a method to do what I want
}
It works perfectly for now, when isConfirmed is true, postback occurs and Page_Load method fires, then the if condition gives me what I want.
References:
Check
Ensure that __doPostBack() function is implemented on the page