calling a button click event - c#

Is it possible to call "button click event" in one web form ,from a button in another web form?
what actually i'm trying to do is, i've a link button in second form, when it is clicked, i want the first form to disply and also button in first form to be clicked.
can anyone help me do this?

I assume you are using jQuery and have basic knowledge of it. So do it this way:
<form id="form1" style="display:none">
<Asp:Button id="button1" onclick="alert('clicked')" >button1</Asp:Button>
</form>
<form id="form2">
<Asp:LinkButton url="javascript:void(0);" onclick="call1();">Link button1</Asp:LinkButton>
</form>
<script>
function call1()
{
$("#form1").show();
$("#button1").trigger("click");
}
</script>
Note: The asp markup written by me can give compilation errors, so please resolve those yourself. I put that just to give you the basic idea of how it is handled.

create a Delegate in WebForms (I have used in WinForms)
public delegate void LoginDelegate(string s);
loginAirLineDelegate = new LoginDelegate(DisableToolStripMenuItems);
public void DisableToolStripMenuItems(string s)
{
this.viewToolStripMenuItem.Visible = true;
this.bookingToolStripMenuItem.Visible = true;
this.existingUserToolStripMenuItem.Visible = false;
this.newUserToolStripMenuItem.Visible = false;
this.toolStripStatusUserID.Text = "USerID :- "+s;
this.LoginUserId = s;
}
I have passed the Delaqgte to other Form with Construtor as argumnet.
I can able to fire the delegate from the second form like this
logDelegate(textBoxUserName.Text);

Related

Textbox.text always returns empty string in code behind c#

Well, I'm trying to do a simple command: get the text from TextBox. I've searched for that, but every answer failed for me.
In my code aspx:
<form id="form1" runat="server" method="post">
<div class="form">
<div class="form-search ngen-search-form">
<span id="search-trigger" class="form-search-submit">
<img src="Imagens/Lupa_Icon 2.png" id="lupa"/>
</span>
<asp:TextBox ID="txtBoxSearch" runat="server" CssClass="form-search-input" placeholder="Pesquise..." ViewStateMode="Enabled"/>
</div>
</div>
</form>
I have a Javascript function that verifies what key my client pressed:
$(document).keypress(function(e) {
if(e.which == 13){
if( document.getElementById("txtBoxSearch").value == "" ) return true;
else {
<% setSearch(); %>
document.getElementById("testeArv").innerHTML='<%=search.ToString()%>';
return false;
}
}// First if
});
And finally, my function setSearch() in code behind is:
public void setSearch( )
{
if( !Page.IsPostBack ) {
search = txtBoxSearch.Text;
}
}
Main mistake is about how to call codebehind method in jQuery. Take a look here
to know how to do it. Summary: you need ajax
Then you will have to keep in mind that it does Page.IsPostBack.
With !Page.IsPostBack you are saying "first page access" but when you press the button !Page.IsPostBack will be false. If you try the same example so:
public void setSearch( )
{
if(!Page.IsPostBack) {
// First page access
search = txtBoxSearch.Text;
} else {
// The page has been reloaded
search = txtBoxSearch.Text;
}
}
It will work. (The else will run)
I am not sure but I have tried it (without jQuery) with a button and the same error occurs. You want to run the function when the Enter is pressed so the page will do the reload. Take a look here.
Maybe it helps you in some way.
It's the <form> tag blocking your way to get the value in post back. Remove the <form> tag and use AutoPostBack=true for your text box. You won't need to use jQuery to catch the event and the value.
You can't call code behind code from client-side code. They execute on different machines.

Check li click value

I m using two list items with link. Now I want to check which link was clicked from the client side. Here is my code:
<ul id="navtabs">
<li id="basic" runat="server" class="cat-item cat-item-6 current-cat">new</li>
<li id="new" runat="server" class="cat-item cat-item-8">old</li>
</ul>
I want to check which item am click whether basic or new
if(this.basic.clicked ==true)
{
do something
}
else
{
do something
}
How can I do this?
If you are suing Web forms then,
The the control which are suing must be server control
If it is a link the put runat="server" and id of the control
Create on click event of every link.
But what is the purpose of those link is not clear.
What action do you want to take on the click must be clear.
I have a trick for it. You can do this with help of jQuery, one hidden field & one hidden asp button.
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Hidden Button" />
<asp:HiddenField ID="hdnLIClicked" runat="server" />
Now jQuery part, in ready event
$().ready(function() {
$("#Button1").hide();//hiding the button through jQuery
$("#basic").click(function(){
$("#hdnLIClicked").val("basic");
$("#Button1").click();
});
$("#new").click(function(){
$("#hdnLIClicked").val("new");
$("#Button1").click();
});
});
Or you can give a common class to all your list items, if there are more list items, like you already have a common class for both of your list items. i.e "cat-item".
$().ready(function() {
$("#Button1").hide();//hiding the button through jQuery
$(".cat-item").click(function(){
$("#hdnLIClicked").val($(this).attr("id"));
$("#Button1").click();//this will fire the hidden button event on server side.
});
});
And you'll have which 'li' was clicked in the hiddenfield.
On backend, handle the button click event like this.
protected void Button1_Click(object sender, EventArgs e)
{
if (hdnLIClicked.Value == "basic")
{
//handle your logic for basic here...
}
else if (hdnLIClicked.Value == "new")
{
//handle your logic for new here...
}
}
Hide the button through jQuery, don't set its property Visible="false", or the button won't get rendered on client side.
Enjoy ;)...

Fetch JS return value in server side page_load event in asp.net

I have an aspx master/content page scenario. The parent page has an IFrame which points to a child.aspx. The child.aspx has a checkbox, On page_load of child.aspx, I want to show/hide the checkbox depending on the following logic:
- if the child.aspx is opened directly, then I have to show the checkbox.
- if the child.aspx is opened in the IFrame, then I have to hide the checkbox.
Basically, I want to check in child.aspx, if it contains a parent window then hide the checkbox control otherwise show it.
I will prefer the show/hide code in codebehind in Page_load event as I have to execute some more logic depending on whether the it is opened from parent window or not.
Till now I did the following:
In child.aspx
<asp:Content ID="Content1" ContentPlaceHolderID="Main" Runat="Server">
<script language="javascript" type="text/javascript">
function DoesParentExists()
{
var bool = (parent.location == window.location)? false : true;
var HClientID ='<%=hfDoesParentExist.ClientID%>';
document.getElementById(HClientID).Value = bool;
}
</script>
<div>
<h2>Content - In IFrame</h2>
<asp:HiddenField runat="server" id="hfDoesParentExist" />
<asp:CheckBox ID="chkValid" runat="server" />
<asp:ImageButton ID="ImageButton_FillW8Online" ImageUrl="~/images/expand.gif"
OnClick="btnVerify_Click" runat="server" style="height: 11px" />
</div>
</asp:Content>
in client.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "DoesParentExists", "DoesParentExists()", true);
if (hfDoesParentExist.Value == "true")
{
chkValid.Visible = false;
}
}
Using RegisterClientScriptBlock, I get error in JS. That the object hfDoesParentExist doesn't exist 'coz the control is not yet created. Right? I tried using RegisterStartupScript but in codebehind I always get null in hidden variable. I don't want to use the on button click or something like it. I need it on page_load event only. How to resolve the issue?
This line:
document.getElementById(HClientID).Value = bool;
Should be: (lower case value)
document.getElementById(HClientID).value = bool;
Also you cannot check the value of a hidden field set by javascript register callback, in the current executing context on the server side.
I would move the logic to the client side to hide or show the checkbox. If the field must indeed be removed from the page you can do that as well with javascript.
function DoesParentExists()
{
var bool = (parent.location == window.location)? false : true;
var cehckboxId ='<%=chkValid.ClientID%>';
if(bool){
document.getElementById(cehckboxId).style.display = 'none';
}
else {
document.getElementById(cehckboxId).style.display = 'block';
}
}
You may want to wrap the checkbox with a div and hide the container also to include the label.
To do it server-side, I would rely on a querystring parameter. Have the parent page load the child page by appending ?inframe=1. Then check for that value in your Page_Load.

ASP.Net double-click problem

having a slight problem with an ASP.net page of mine. If a user were to double click on a "submit" button it will write to the database twice (i.e. carry out the 'onclick' method on the imagebutton twice)
How can I make it so that if a user clicks on the imagebutton, just the imagebutton is disabled?
I've tried:
<asp:ImageButton
runat="server"
ID="VerifyStepContinue"
ImageUrl=image src
ToolTip="Go"
TabIndex="98"
CausesValidation="true"
OnClick="methodName"
OnClientClick="this.disabled = true;" />
But this OnClientClick property completely stops the page from being submitted! Any help?
Sorry, yes, I do have Validation controls... hence the icky problem.
Working on this still, up to this point now:
ASP code:
<asp:TextBox ID="hidToken" runat="server" Visible="False" Enabled="False"></asp:TextBox>
...
<asp:ImageButton runat="server" ID="InputStepContinue" Name="InputStepContinue" ImageUrl="imagesrc" ToolTip="Go" TabIndex="98" CausesValidation="true" OnClick="SubmitMethod" OnClientClick="document.getElementById('InputStepContinue').style.visibility='hidden';" />
C# code:
private Random
random = new Random();
protected void Page_Load(object sender, EventArgs e)
{
//Use a Token to make sure it has only been clicked once.
if (Page.IsPostBack)
{
if (double.Parse(hidToken.Text) == ((double)Session["NextToken"]))
{
InputMethod();
}
else
{
// double click
}
}
double next = random.Next();
hidToken.Text = next + "";
Session["NextToken"] = next;
Actually... this nearly works. The double click problem is pretty much fixed (yay!) The image still isn't hidden though.
The general approach is twofold.
Serverside:
On load of the page, generate a token (using System.Random), save it in the session, and write it to a hidden form field
On submit, check that the hidden form field equals the session variable (before setting it again)
Do work
Clientside:
Similar to what you have, but probably just hide the button, and replace it with some text like 'submitting'.
The important thing to note, client side, is that the user may cancel the post by hitting 'escape', so you should consider what to do here (depending on how far along they are the token won't be used, so you'll need to bring the button back from being disabled/hidden).
Complete example follows:
C# (includes code to see it in action):
<html>
<head runat="server">
<title>double-click test</title>
<script language="c#" runat="server">
private Random
random = new Random();
private static int
TEST = 0;
public void Page_Load (object sender, EventArgs ea)
{
SetToken();
}
private void btnTest_Click (object sender, EventArgs ea)
{
if( IsTokenValid() ){
DoWork();
} else {
// double click
ltlResult.Text = "double click!";
}
}
private bool IsTokenValid ()
{
bool result = double.Parse(hidToken.Value) == ((double) Session["NextToken"]);
SetToken();
return result;
}
private void SetToken ()
{
double next = random.Next();
hidToken.Value = next + "";
Session["NextToken"] = next;
}
private void DoWork ()
{
TEST++;
ltlResult.Text = "DoWork(): " + TEST + ".";
}
</script>
</head>
<body>
<script language="javascript">
var last = null;
function f (obj)
{
obj.src = "http://www.gravatar.com/avatar/4659883ec420f39723c3df6ed99971b9?s=32&d=identicon&r=PG";
// Note: Disabling it here produced strange results. More investigation required.
last = obj;
setTimeout("reset()", 1 * 1000);
return true;
}
function reset ()
{
last.src = "http://www.gravatar.com/avatar/495ce8981a5127a9fd24bd72e7e3664a?s=32&d=identicon&r=PG";
last.disabled = "false";
}
</script>
<form id="form1" runat="server">
<asp:HiddenField runat="server" ID="hidToken" />
<asp:ImageButton runat="server" ID="btnTest"
OnClientClick="return f(this);"
ImageUrl="http://www.gravatar.com/avatar/495ce8981a5127a9fd24bd72e7e3664a?s=32&d=identicon&r=PG" OnClick="btnTest_Click" />
<pre>Result: <asp:Literal runat="server" ID="ltlResult" /></pre>
</form>
</body>
</html>
If you have validation on the page, disabling the button client side gets a little tricky. If validation fails, you don't want to disable the button. Here's a snippet that adds the client side event handler:
private void BuildClickOnceButton(WebControl ctl)
{
System.Text.StringBuilder sbValid = new System.Text.StringBuilder();
sbValid.Append("if (typeof(Page_ClientValidate) == 'function') { ");
sbValid.Append("if (Page_ClientValidate() == false) { return false; }} ");
sbValid.Append(ctl.ClientID + ".value = 'Please wait...';");
sbValid.Append(ctl.ClientID + ".disabled = true;");
// GetPostBackEventReference obtains a reference to a client-side script
// function that causes the server to post back to the page.
sbValid.Append(ClientScript.GetPostBackEventReference(ctl, ""));
sbValid.Append(";");
ctl.Attributes.Add("onclick", sbValid.ToString());
}
See this asp.net thread for more info.
Update: the above code would be used to add the OnClientClick handler in code behind. You could also write the javascript in your aspx markup like so:
<script type="text/javascript">
function disableButton(button)
{
// if there are client validators on the page
if (typeof(Page_ClientValidate) == 'function')
{
// if validation failed return false
// this will cancel the click event
if (Page_ClientValidate() == false)
{
return false;
}
}
// change the button text (does not apply to an ImageButton)
//button.value = "Please wait ...";
// disable the button
button.disabled = true;
// fire postback
__doPostBack(button.id, '');
}
</script>
<asp:ImageButton runat="server" ID="VerifyStepContinue" ImageUrl="button.png"
ToolTip="Go" TabIndex="98" CausesValidation="true" OnClick="methodName"
OnClientClick="return disableButton(this);" />
I have solved this by setting a hidden field on the client click before hitting the server.
Then in the server I check the hidden field and if the value is for example something 'FALSE' that might mean I can or cannot of the action.
Similar to Silky's client-side response, I usually make two buttons that look alike except that the second button is disabled and hidden. OnClientClick of the normal button swaps the display styles of the two buttons so that the normal button is hidden and the disabled button is shown.
The double-click feature is a server-side implementation to prevent processing that same request which can be implemented on the client side through JavaScript. The main purpose of the feature is to prevent processing the same request twice. The server-side implementation does this by identifying the repeated request; however, the ideal solution is to prevent this from occurring on the client side.
In the HTML content sent to the client that allows them to submit requests, a small validation JavaScript can be used to check whether the request has already been submitted and if so, prevent the online shopper from submitting the request again. This JavaScript validation function will check the global flag to see if the request has been submitted and, if so; does not resubmit the request. If the double-click feature is disabled on the server, it is highly recommended that the JSP and HTML pages implement this JavaScript prevention.
The following example prevents the form from being submitted more then once by using the onSubmit() action of the form object:
...
<script>
var requestSubmitted = false;
function submitRequest() {
if (!requestSubmitted ) {
requestSubmitted = true;
return true;
}
return false;
}
</script>
...
<FORM method="POST" action="Logon" onSubmit="javascript:submitRequest()">
......
</FORM>
for those who just want to do a quick fix , just hide it and show another button that has no events
<asp:Button ID="RedeemSubmitButton" runat="server" Text="Submit to Redeem" OnClick="RedeemSubmitButton_Click" OnClientClick="hideit();" />
<asp:Button ID="RedeemSubmitButtonDisabled" style="display:none;" runat="server" Text="please wait" OnClientClick="javascript:alert('please wait, processing');" />
<script>
function hideit() {
var btn = $get('<%= this.RedeemSubmitButton.ClientID %>');
var btn2 = $get('<%= this.RedeemSubmitButtonDisabled.ClientID %>');
if (btn != null)
{
btn.style.display = 'none';
btn2.style.display = 'block'
}
}
</script>

Confirmation dialog at runtime in asp.net

I have a simple content management system that stores pages by Pagename and Version. After clicking on Save, my code (server side) checks for the existence of Pagename/Version.
If it exists I would like to display a confirmation dialog box, which asks the user to confirm whether or not the current Pagename/Version should be replaced.
What is the easiest way to accomplish this? Thanks.
<asp:Button OnClientClick="return confirm('Are you sure you want to go?');"
Text="Confirm" runat="server" onclick="Unnamed1_Click" />
If they click OK, the server onclick event will happen, if they click cancel, it will be like they didn't even press the button, of course, you can always add functionallity to the cancel part.
Maybe something like:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
<script type="text/javascript">
function CompareConfirm()
{
var str1 = "abc";
var str2 = "def";
if (str1 === str2) {
// your logic here
return false;
} else {
// your logic here
return confirm("Confirm?");
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button OnClientClick="return CompareConfirm();"
Text="Confirm" runat="server" onclick="Unnamed1_Click" />
</div>
</form>
</body>
</html>
I appreciate both previous answers and they were helpful but not exactly what I was looking for. After considering the responses and doing more research I'm posting my solution so that maybe it will help someone else.
Button code:
<asp:Button ID="btnSave" OnClick="btnSaveClick" runat="server" Text="Save" OnClientClick="return CheckForVersion()" />
Javascript:
<script language="javascript">
function CheckForVersion() {
PageMethods.CheckForVersion(aspnetForm.ctl00$ContentPlaceHolder1$ddlPageName2.value, aspnetForm.ctl00$ContentPlaceHolder1$txtContentName2.value, OnSucceeded, OnFailed);
return false;
}
function OnSucceeded(results) {
if(results) {
//version exists so prompt user
if(confirm("Version already exists. Do you want to overwrite?")) {
__doPostBack('ctl00$ContentPlaceHolder1$btnSave','');
}
}
else
{
//version does not exist so save it without prompting user
__doPostBack('ctl00$ContentPlaceHolder1$btnSave','');
}
}
function OnFailed(error) {
// handle pagemethod error
alert(error.get_message());
}
</script>
C# using Subsonic 2.1:
[WebMethod]
public static bool CheckForVersion(string pageName, string versionName)
{
PageContentCollection pages = new PageContentCollection().Where("pageName", pageName).Where("versionName", versionName).Load();
if (pages.Count > 0)
return true;
else
return false;
}
An alternative, simpler approach which doesn't require AJAX would be to allow the post-back as normal, then in the code-behind, do your checks.
If the user confirmation is required, just return the user back to the same page but make an extra panel visible and hide the original 'Save' button.
In this extra panel, display your message with another OK / Cancel button. When the user clicks this OK button, perform the save!
Put the check before rendering the page to the client. Then attach a handler (on the client side, eg. javascript) to the save-button or form that displays the confirmation box (but only if the saving results in a replacement).
add a hidden field to your page for example Hiddenfield1
then add this function
public bool Confirm(string MSG)
{
string tmp = "";
tmp = "<script language='javascript'>";
tmp += "document.getElementById('HiddenField1').value=0; if(confirm('" + MSG + "')) document.getElementById('HiddenField1').value=1;";
tmp += "</script>";
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "ConfirmBox", tmp);
if(HiddenField1.Value.Trim()=="0") return false;
return true;
}

Categories