how to use image button to open the url in another window - asp.net

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

Related

How to avoid Page_Load() on button click?

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

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 display an image in a new window

I have a follow-on question to How to display an image based on SelectedValue in a GridView?
What I would really like to do is have a ViewImage button on my GridView control so that when that is clicked, the image is displayed on a new page in a new browser window. How would I do that? I'm thinking perhaps do I need to create a
<asp:ButtonField>
How do I handle the click and how do I get the image to diplay on a new form in a new web browser window?
Thanks very much for looking.
You can use TemplateColumn, in that TemplateColumn you can define a button where you put javascript function to open new window.
Example:
<asp:TemplateField>
<ItemTemplate>
<input type="button" onclick="javascript:ShowImageInNewPage('PageToShowImage.aspx?tradeId=<%# Eval("TradeId") %>');" />
</ItemTemplate>
</asp:TemplateField>
The "ShowImageInNewPage" function is a custom function you declare to popup/open new window with the selected image url.
In PageToShowImage.aspx, declare an img tag:
<asp:Image ID="imgBlah" runat="server" />
In code behind of PageToShowImage.aspx:
protected void Page_Load(object sender, EventArgs e)
{
// this is querystring from GridView page
if(Request.QueryString["tradeId"] != null)
{
imgBlah.Src = "GetImage.aspx?entityId=" + tradeId + "&entityType=T";
}
else
{
imgBlah.Src = "~/images/no-image.jpg"; // set no image
}
}
HTH
I'm hoping that you're dealing with browser supported image formats. Assuming you are, you don't need a ButtonField. One approach would be to use an <asp:HyperLink> in a TemplateColumn, as Arief suggested.
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="hyperLink1" runat="server" NavigatUrl="UrlToYourViewImagePage" Text="View Image" />
</ItemTemplate>
</asp:TemplateField>
If you want the image to open in a new window, build a window.open call for each HyperLink's NavigateUrl.

ImageButton not hitting codebind method, but does if replaced with LinkButton

I have an ImageButton being build inside of radgridview columnn. It is defined as follows.
<asp:ImageButton ID="ImageButton_DeleteRun" ImageUrl="~/Assets/Images/Misc/delete.png"
runat="server" OnClick="QueryDelete" CommandName="QueryDelete"
CommandArgument='<%# DataBinder.Eval(Container,"DataItem.QueryGuid") %>'
Width="10" Height="10" />
It loads properly. When I click on it, I expect to hit the following codebehind method:
protected void QueryDelete(object sender, EventArgs e)
{
/* A bunch of code*/
}
It never gets there. What is more fustrating is that if I replace the ImageButton with
<asp:LinkButton ID="ImageButton_DeleteRun" Text="X"
runat="server" OnClick="QueryDelete" CommandName="QueryDelete"
CommandArgument='<%# DataBinder.Eval(Container,"DataItem.QueryGuid") %>'/>
It works perfectly.
Is there something wrong with ImageButton? Am I missing something?
EDIT - New info
Basically when the image button is rendered, there is no href.
Weird--
<input type="image" style="height: 10px; width: 10px; border-width: 0px;" src="../Assets/Images/Misc/delete.jpg"
id="ctl00_ctl00_ctl00_AllContent_MainContent_MainContent_controlPanelQueryHistory_saved_RadGridQueryHistory_ctl00_ctl04_ImageButton1"
name="ctl00$ctl00$ctl00$AllContent$MainContent$MainContent$controlPanelQueryHistory_saved$RadGridQueryHistory$ctl00$ctl04$ImageButton1"/>
<a
href="javascript:__doPostBack('ctl00$ctl00$ctl00$AllContent$MainContent$MainContent$controlPanelQueryHistory_saved$RadGridQueryHistory$ctl00$ctl04$ImageButton_DeleteRun','')"
id="ctl00_ctl00_ctl00_AllContent_MainContent_MainContent_controlPanelQueryHistory_saved_RadGridQueryHistory_ctl00_ctl04_ImageButton_DeleteRun">delete</a>
As a work around you could try wrapping an image within a LinkButton.
<asp:LinkButton ID="ImageButton_DeleteRun" Text="X"
runat="server" OnClick="QueryDelete" CommandName="QueryDelete"
CommandArgument='<%# DataBinder.Eval(Container,"DataItem.QueryGuid") %>'>
<img src="~/Assets/Images/Misc/delete.png" />
</asp:LinkButton>
Maybe the page is validating? If so, try adding CausesValidation=false to the ImageButton.
You may want to try replacing OnClick with OnCommand to see if that solves the problem.
Silly question - but is the ImageUrl rendering a valid image or red-x?
Put both link types in the page and then "View Source" on the resulting page. This may give you some clues as to what is happening. It may be rendering the ImageButton in a way that JavaScript or CSS is messing up.
How do you get the command arguments in OnClick? You have an EventArgs.
The OnCommand handler has CommandEventArgs containing the CommandName and CommandArguments:
protected void image_Command(object sender, CommandEventArgs e)
{
}
It would make sense to use the OnCommand.

Disable the postback on an <ASP:LinkButton>

I have an ASP.NET linkbutton control on my form. I would like to use it for javascript on the client side and prevent it from posting back to the server. (I'd like to use the linkbutton control so I can skin it and disable it in some cases, so a straight up tag is not preferred).
How do I prevent it from posting back to the server?
ASPX code:
<asp:LinkButton ID="someID" runat="server" Text="clicky"></asp:LinkButton>
Code behind:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
someID.Attributes.Add("onClick", "return false;");
}
}
What renders as HTML is:
<a onclick="return false;" id="someID" href="javascript:__doPostBack('someID','')">clicky</a>
In this case, what happens is the onclick functionality becomes your validator. If it is false, the "href" link is not executed; however, if it is true the href will get executed. This eliminates your post back.
This may sound like an unhelpful answer ... But why are you using a LinkButton for something purely client-side? Use a standard HTML anchor tag and set its onclick action to your Javascript.
If you need the server to generate the text of that link, then use an asp:Label as the content between the anchor's start and end tags.
If you need to dynamically change the script behavior based on server-side code, consider asp:Literal as a technique.
But unless you're doing server-side activity from the Click event of the LinkButton, there just doesn't seem to be much point to using it here.
You can do it too
...LinkButton ID="BtnForgotPassword" runat="server" OnClientClick="ChangeText('1');return false"...
And it stop the link button postback
Just set href="#"
<asp:LinkButton ID="myLink" runat="server" href="#">Click Me</asp:LinkButton>
I think you should investigate using a HyperLink control. It's a server-side control (so you can manipulate visibility and such from code), but it omits a regular ol' anchor tag and doesn't cause a postback.
Just been through this, the correct way to do it is to use:
OnClientClick
return false
as in the following example line of code:
<asp:LinkButton ID="lbtnNext" runat="server" OnClientClick="findAllOccurences(); return false;" />
In C#, you'd do something like this:
MyButton.Attributes.Add("onclick", "put your javascript here including... return false;");
Instead of implement the attribute:
public partial class _Default : System.Web.UI.Page{
protected void Page_Load(object sender, EventArgs e)
{
someID.Attributes.Add("onClick", "return false;");
}}
Use:
OnClientClick="return false;"
inside of asp:LinkButton tag
To avoid refresh of page, if the return false is not working with asp:LinkButton use
href="javascript: void;"
or
href="#"
along with OnClientClick="return false;"
<asp:LinkButton ID="linkPrint" runat="server" CausesValidation="False" href="javascript: void;"
OnClientClick="javascript:self.print();return false;">Print</asp:LinkButton>
Above is code will call the browser print without refresh the page.
call java script function on onclick event.
Have you tried to use the OnClientClick?
var myLinkButton = new LinkButton { Text = "Click Here", OnClientClick = "JavaScript: return false;" };
<asp:LinkButton ID="someID" runat="server" Text="clicky" OnClientClick="JavaScript: return false;"></asp:LinkButton>
Something else you can do, if you want to preserve your scroll position is this:
<asp:LinkButton runat="server" id="someId" href="javascript: void;" Text="Click Me" />
Why not use an empty ajax update panel and wire the linkbutton's click event to it? This way only the update panel will get updated, thus avoiding a postback and allowing you to run your javascript
No one seems to be doing it like this:
createEventLinkButton.Attributes.Add("onClick", " if (this.innerHTML == 'Please Wait') { return false; } else { this.innerHTML='Please Wait'; }");
This seems to be the only way that works.
In the jquery ready function you can do something like below -
var hrefcode = $('a[id*=linkbutton]').attr('href').split(':');
var onclickcode = "javascript: if`(Condition()) {" + hrefcode[1] + ";}";
$('a[id*=linkbutton]').attr('href', onclickcode);
You might also want to have the client-side function return false.
<asp:LinkButton runat="server" id="button" Text="Click Me" OnClick="myfunction();return false;" AutoPostBack="false" />
You might also consider:
<span runat="server" id="clickableSpan" onclick="myfunction();" class="clickable">Click Me</span>
I use the clickable class to set things like pointer, color, etc. so that its appearance is similar to an anchor tag, but I don't have to worry about it getting posted back or having to do the href="javascript:void(0);" trick.
use html link instead of asp link and you can use label in between html link for server side
control

Resources