How to avoid Page_Load() on button click? - asp.net

I have two buttons, preview and Save. With help of preview button user can view the data based on the format and then can save.
But when preview is clicked, one textbox attached to ajaxcontrol (Calender) becomes empty and user have to fill the date before saving. How to handle this? On preview click i get the details to show the data in layout.
<asp:TextBox ID="txtDate" ReadOnly="true" runat="server"></asp:TextBox>
<div style="float: right;">
<asp:ImageButton ID="imgcalender1" runat="server" ImageUrl="~/images/calendar.png"
ImageAlign="Bottom" />
<asp:CalendarExtender ID="ajCal" TargetControlID="txtpublishDate" PopupButtonID="imgcalender1"
runat="server">
</asp:CalendarExtender>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" ValidationGroup="group1" runat="server" ControlToValidate="txtDate"
ForeColor="Red" Font-Bold="true" ErrorMessage="*"></asp:RequiredFieldValidator>
</div>
<asp:Button ID="btnPreview" runat="server" Text="Preview" OnClick="btnPreview_Click" />
<asp:Button ID="btnsubmit" runat="server" ValidationGroup="group1" Text="Save" OnClick="btnsubmit_Click" />

Use Page.IsPostback() in your aspx code (server-side). Like this:
private void Page_Load()
{
if (!IsPostBack)
{
// the code that only needs to run once goes here
}
}
This code will only run the first time the page is loaded and avoids stepping on user-entered changes to the form.

From what I am understanding the preview button is causing a postback and you do not want that, try this on your preview button:
<asp:button runat="server".... OnClientClick="return false;" />
similarly this also works:
YourButton.Attributes.Add("onclick", return false");
Edit:
it seems the answer to the user's question was simple change in the HTML mark up of the preview button
CausesValidation="False"

you can put your code in
Page_Init()
{
//put your code here
}
instead of
Page_Load()
{
//code
}

I had the same problem and the solution above of "CausesValidation="False"" and even adding "UseSubmitBehavior="False"" DID NOT work - it still called "Page_Load" method.
What worked for me was adding the following line up front in Page_Load method.
if (IsPostBack) return;
I am mentioning this if it helps someone (I meant to comment above but StackOverflow did not allow me to comment because I am a new user - hence a new reply).

Try adding this to the buttons properties in the aspx page.
OnClientClick="return false;"

For my the #tgolisch answer worked better, maybe it's because i'm still a rookie.
I was trying to load a simple captcha in my WebForm and end up using a Reference Type in the Page_Load event and in a Button Click event (for a code snippet).
In the end i only have to edit some things and it's done:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var captchaText = generateCaptchaCode(5);
lblCaptcha.Text = captchaText;
}
}
protected void btnCheckCaptcha_Click(object sender, EventArgs e)
{
if (txtCaptchaCode.Text == lblCaptcha.Text)
lblMessage.Text = "Right input characters";
else
lblMessage.Text = "Error wrong characters";
}

form1.Action = Request.RawUrl;
Write this code on page load then page is not post back on button click

Related

Disable Button after click in dnn

for one requirements i need to disable button after click and run server side code after disabled for this i have used below code which is called at pageload
btnGREntry.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(btnGREntry, "") +
";this.value='Please wait...';this.disabled = true;");
but it is giving me below error.
An unknown error occurred while processing the request on the server.
The status code returned from the server was: 0
please help me to find out a solution or suggest any other solution to disable button after click
Note: similar things are working in asp.net but i am using in *dotnetnuke version 7.0 *
You can do this in the code-behind.
ASPX
<asp:Button ID="Button1" runat="server" onclick="Button1_Click1" Text="Button" />
Code-behind
protected void Button1_Click1(object sender, EventArgs e)
{
Button a = (Button)sender;
a.Enabled = false;
}
Does the button have to remain disabled continuously or is it to return to enabled after page refresh? In the former case then handle it with both JavaScript and code behind. In the later case handle it with just JavaScript.
<asp:Button ID="Button1" runat="server" onClientClick="DisableButton();" onclick="Button1_Click1" Text="Button" />
JavaScript:
function DisableButton() {
var btn = $("#buttonID").attr("disabled", "disabled");
}

Two Buttons updating one item of a listview

I have two buttons in a ListView. With a click on the first Button I want to update the ListView-Item. With a click on the second button i want to update the ListView-Item and redirect to a different page. Both Buttons have a property CommandName="Update". I wanted to solve my problem with the CommandArgument-Property and the OnItemUpdated-Event, but I do not know how to get the value of this Property in the event.
<asp:ObjectDataSource ID="ods" runat="server" SelectMethod="Select" UpdateMethod="Update">
<SelectParameters>
<asp:Parameter ..... />
</SelectParameters>
<UpdateParameters>
<asp:Parameters .... />
</UpdateParameters>
</asp:ObjectDataSource>
<asp:ListView ID="lv" runat="server" DataSourceID="ods" DataKeyNames="ID" OnItemUpdated="lv_OnItemUpdated">
<ItemTemplate>...</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="btnUpdate" runat="server" CommandName="Update"/>
<asp:Button ID="btnUpdate2" runat="server" CommandName="Update"/>
</EditItemTemplate>
</asp:ListView>
And in codebehind:
protected void lv_OnItemUpdated(object sender, ListViewUpdateEventArgs e)
{
...
}
Is it possible to decide in lv_OnItemUpdated which Button the user clicked?
I don't believe there is a way to distinguish which control issued the Update command, since sender is the ListView itself.
A workaround would be for you to give one button the CommandName "Update", and the other "UpdateRedirect".
The "UpdateRedirect" button will fire the ListView_ItemCommand event, and from there you can call ListView.UpdateItem, keeping your updating logic in there, and then redirect next.
Why do you insist on using the OnItemUpdated event?
Well there are 2 to 3 ways of doing it: One is of CommandArgument as:
<asp:Button id="Button1"
Text="Sort Ascending"
CommandName="Sort"
CommandArgument="Ascending"
OnCommand="CommandBtn_Click"
runat="server"/>
<asp:Button id="Button2"
Text="Sort Descending"
CommandName="Sort"
CommandArgument="Descending"
OnCommand="CommandBtn_Click"
runat="server"/>
and than on server side you can have:
void CommandBtn_Click(Object sender, CommandEventArgs e)
{
if(e.CommandName == "Sort")
//do you work and so on
}
or you can cast the sender as button and take it ID to see, which button was it:
((Button)sender)).ID
or you can get button ID as:
String ButtonID = Request["__EVENTTARGET"];
I hope it will help you in fixing your problem.
so you can have like:
protected void lv_OnItemUpdated(object sender, ListViewUpdateEventArgs e)
{
// either use e.CommandName
// or user ((Button)sender)).ID
}
Give each button a distinct name. Have the same event handling method in your code behind handle both button click events. Then check which button called the method.
EDIT: A workaround would be to use javascript to put the name of the clicked button into a hidden field on the form BEFORE it goes server side (using a client side script). Then in your Listview you could check the value of the hidden field to see which button was clicked.
Ok, yes, the itemcommand is what you want:
The lifecycle for an update or insert triggers both their native events AND the itemcommand event. The itemCommand event will occur prior to the itemUpdating or the itemInserting events.
So, you can create a boolean variable called called "bSecondButtonClicked" for example Add the command argument to both buttons with the Commandname='UPDATE". the e.command argument can be evaluated at the itemcommand event point. There set your Boolean variable (or however you implement it) to true. Then, at the itemupdating event, trigger your code based on the bSecondButtonClicked.
You need to get into the ItemCommand event of your ListView
protected void lstvw_ItemCommand(object sender, ListViewCommandEventArgs e)
{
switch (e.CommandName)
{
case "new":
try
{
//e.CommandArgument
//e.CommandSource
// do your stuff here
}
catch (Exception ex)
{
}
break;
default:
break;
}
}

How to hide link button based on a result returned by a class ?

I am bit new to C# and got a question.
I have a class as below that simply return false ( this is just to test)
public class SetAuthority
{
public SetAuthority()
{
//
// TODO: Add constructor logic here
//
}
public static Boolean AuthorizedToAddEdit()
{
return false;
}
}
I have a DetailsView with two link buttons to Edit and add New record. I want to hide the link buttons based on the above class method returning value.
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" visible='<%# SetAuthority.AuthorizedToAddEdit() %>'
CommandName="Edit" Text="Edit"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" visible='<%# SetAuthority.AuthorizedToAddEdit() %>'
CommandName="New" Text="New"></asp:LinkButton>
</ItemTemplate>
Above works file and Edit and New link buttons are hidden when I run the program.
But the question is, I have a separate link button outside of the DetailsView. It is just a link to navigate to another page. I want to hide this in similar way using the same logic. I have the below code in my webform.
<asp:LinkButton ID="LinkButton5" runat="server" CausesValidation="False" visible='<%# SetAuthority.AuthorizedToAddEdit() %>'
CommandName="OpenAdminPage" Text="Open Admin Page"></asp:LinkButton>
But the link button is always visible and seems it is not calling the class and not getting the value back. It appeared to be the class not return any value and can someone help me to identify what is the different between having this and working in DetailsView and not working for a simple link button.
Note: have a workaround where I can call the same method in Page Load event that works fine without any issue. Code is below
protected void Page_Load(object sender, EventArgs e)
{
Boolean myAllowAdd;
myAllowAdd = SetAuthority.AuthorizedToAddEdit();
if (myAllowAdd == false)
{
LinkButton1.Visible = false;
}
}
The reason is that this is for databinding expressions only: <%# Since the DetailsView is databound it works there.
If you would DataBind the page it worked also for the LinkButton outside of the DetailsView:
protected void Page_Load(object sender, EventArgs e)
{
Page.DataBind();
}
inline asp.net tags... sorting them all out (<%$, <%=, <%, <%#, etc.)
Side-note: be careful with static in ASP.NET. The static method does not yet hurt. But if you'd also use static fields you'd enter a minefield since it would be shared across all requests. Your current code-behind "work-around" is the better approach anyway.

how to open a page in new tab on button click in asp.net?

I want to open a page in new tab of browser on button click.
I have searched a lot on google but i couldn't find anything.
Here is my button.
<asp:Button ID="btnNewEntry" runat="Server" CssClass="button" Text="New Entry" OnClick="btnNewEntry_Click" />
protected void btnNewEntry_Click(object sender, EventArgs e)
{
Response.Redirect("New.aspx");
}
Can you please help me how i can do this ?
You could use window.open. Like this:
protected void btnNewEntry_Click(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(
this.GetType(),"OpenWindow","window.open('YourURL','_newtab');",true);
}
Why not just call window.open straight from OnClick?
<asp:Button ID="btnNewEntry" runat="Server" CssClass="button" Text="New Entry" OnClick="window.open('New.aspx')" />
Try This
Link
Take care to reset target, otherwise all other calls like Response.Redirect will open in a new tab, which might be not what you want.
<asp:LinkButton OnClientClick="openInNewTab();" .../>
In javaScript:
<script type="text/javascript">
function openInNewTab() {
window.document.forms[0].target = '_blank';
setTimeout(function () { window.document.forms[0].target = ''; }, 0);
}
</script>
Use JavaScript for the main form / Button click event. An example is:
Context.Response.Write("<script language='javascript'>window.open('AccountsStmt.aspx?showledger=" & sledgerGrp & "','_newtab');</script>")
try this rather than redirect...
Response.Write("<script>");
Response.Write("window.open('ClickPicture.aspx','_blank')");
Response.Write("</script>");
Just had the same problem. Client-side wasn't appropriate because the button was posting back information from a listview.
Saw same solution as Amaranth's on way2coding but this didn't work for me.
However, in the comments, someone posted a similar solution that does work
OnClientClick="document.getElementById('form1').target ='_blank';"
where form1 is the id of your asp.net form.
You have to use Javascript since code behind is server side only. I am pretty sure that this works.
<asp:Button ID="btnNewEntry" runat="Server" CssClass="button" Text="New Entry" OnClick="btnNewEntry_Click" OnClientClick="aspnetForm.target ='_blank';"/>
protected void btnNewEntry_Click(object sender, EventArgs e)
{
Response.Redirect("New.aspx");
}
Add this Script
<script type = "text/javascript">
function SetTarget() {
document.forms[0].target = "_blank";
}
</script>
and
<asp:Button ID="BTNpRINT" runat="server" Text="PRINT" CssClass="btn btn-primary" OnClick="BTNpRINT_Click" OnClientClick = "SetTarget();"/>
and
protected void BTNpRINT_Click(object sender, EventArgs e)
{
Response.Redirect(string.Format("~/Print.aspx?ID={0}",txtInv.Text));
}
You can add to your button OnClientClick like so:
<asp:Button ID="" runat="Server" Text="" OnClick="btnNewEntry_Click" OnClientClick="target ='_blank';"/>
This will change the current form's target for all buttons to open in new tab. So to complete the fix you can then use 2 approaches:
For any other button in this form, add to client click a "reset form target" function like so:
function ResetTarget() {
window.document.forms[0].target = '';
}
Add the same code inside the function inside a setTimeout() so the code will reset the form's target after few moments. See this answer https://stackoverflow.com/a/40682253/8445364
Per Open a URL in a new tab (and not a new window) using JavaScript
Nothing an author can do can choose to open in a new tab instead of a new window.
The browser decides between opening a new tab or opening a new window. You cannot control this as a developer.
In vb.net either on button click or on link button click, this will work.
System.Web.UI.ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "openModal", "window.open('CertificatePrintViewAll.aspx' ,'_blank');", True)
add target='_blank' after check validation :
<asp:button id="_ButPrint" ValidationGroup="print" OnClientClick="if (Page_ClientValidate()){$('form').attr('target','_blank');}" runat="server" onclick="ButPrint_Click" Text="print" />
You could do this on the ASPX HTML front end to make the button go to a new tab to show page in your ASP.NET site dynamically:
<asp:Button ID="btnNewEntry" CssClass="button" OnClientClick="window.open('https://website','_blank'); return false;" text="WebsiteName" runat="server" />
If the url is dynamic and you want to control it in the code behind
<asp:Button ID="btnNewEntry" runat="Server" Text="New Entry" />
//code behind
var id = 0;
btnNewEntry.OnClientClick = $"window.open('New.aspx?ID={id}')";
A simple solution:
<a href="https://www.google.com" target="_blank">
<button type="button">Open new tab</button>
</a>
You shuld do it by client side. you can place a html hyperlink with target="_blank" and style="display:none".
after that create a javascript function like following
function openwindow(){
$("#hyperlinkid").click();
return false;
}
use this function as onclientclick event handler of the button like onclientclick="return openwindow()"
You need to include a jquery in the page.
Add_ supplier is name of the form
private void add_supplier_Load(object sender, EventArgs e)
{
add_supplier childform = new add_supplier();
childform.MdiParent = this;
childform.Show();
}

how to use image button to open the url in another window

Hi I know how to acheive this in hyperlink by setting target = _blank , how can i do this using image button control , below is my code:
<asp:ImageButton OnClick="test_Click" ImageUrl="/images/contactUs/directionbtn.png" ID="test" runat="server" ValidationGroup="group2" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="txtPostcode1" ErrorMessage="Postcode is required" ValidationGroup="group2"></asp:RequiredFieldValidator>
<br />
Code behind:
protected void test_Click(object sender, ImageClickEventArgs e)
{
Response.Redirect(String.Format("http://maps.google.co.uk/maps?saddr={0}&daddr=&daddr=Wigan+WN6+0HS,+United+Kingdom&iwloc=1&dq=Tangent+Design", txtPostcode1.Text));
}
Any help or advice will be highly appreciated
protected void Page_Load() {
ControlID.Attributes.Add("target", "_blank");
}
If that doesn't work, try adding this to your ImageButton:
<asp:ImageButton runat="server" OnClientClick="window.open('http://url/to/open');" ></asp:ImageButton>
I just figure it out..
On Page_Load event, put
this.Form.Target = "_blank"; // Will set all link's target to a new window
Then for example in a image button Click event, you put:
Response.Redirect("http://stackoverflow.com");
It will simply open this page in a new tab. Try it :)
you could use the Attributes collection to add "target","_blank"
this should add the target attribute to the anchor link surrounding the image
Add target="_blank" to onClientClick will do the trick
In the code behind.
imgbtn.OnClientClick = "target='blank'";
And you're done.
Try this:
<asp:ImageButton OnClick="test_Click" ImageUrl="/images/contactUs/directionbtn.png" ID="test" runat="server" ValidationGroup="group2" OnClientClick="form1.target ='_blank';" />
this.Form.Target = "_blank";
This way the client can see what he wants in a new page, since the server and what is available and his account in the site available at the beginning PageLoad

Resources