Inner image and text of asp:LinkButton disappears after postback - asp.net

I have a link button:
<asp:LinkButton ID="LinkButtonPrint" runat="server" OnClick="OnPrint_Click">
<img src="img/print-icon.png" alt="" />
<asp:Literal runat="server" Text="<%$ Resources:PrintPage %>" />
</asp:LinkButton>
In code behind I add an onclick handler in Page_Load like this:
LinkButtonPrint.Attributes["onclick"] = "StartLoadTracking(this, '" + GetLocalResourceObject("Loading") + "')";
The rendered HTML is like this:
<a href="javascript:__doPostBack('ctl00$LinkButtonPrint','')"
id="ctl00_LinkButtonPrint" onclick="StartLoadTracking(this, 'Loading...');">
<img alt="" src="img/print-icon.png">Print page
</a>
If I click this button it is working OK (it will respond with a PFD file so no HTML is sent back to the browser), but if I click another button on the page (which makes a full postback) the LinkButtonPrint will not have the inner content, it will be rendered like this:
<a href="javascript:__doPostBack('ctl00$LinkButtonPrint','')"
id="ctl00_LinkButtonPrint" onclick="StartLoadTracking(this, 'Loading...');"></a>
If I remove the LinkButtonPrint.Attributes["onclick"] = ... line from Page_Load everything works fine (except my js function is not called, but that is normal).
What am I missing here?
EDIT
This is duplicate of
asp.net Link button image not visible after postback
but that one is not solved either :(

This problem is now known to Microsoft, and they have published an official statement and workaround on the Microsoft Connect issue 718810: LinkButton controls collection lost on postback.
Microsoft statement is:
Thank you for the feedback. This seems like an oddity with the fact that the LinkButton control allows either direct text content via the Text property or in markup, or sub-controls via the Controls collection or markup. The workaround is to use a placeholder as the root content for the control and place the desired mixed content in there, e.g.
<asp:LinkButton runat="server">
<asp:PlaceHolder runat="server">
This is some text.</br>
<asp:Label runat="server">This is a control</asp:Label>
</asp:PlaceHolder>
</asp:LinkButton>

I found the solution:
I had to add runat="server" to the <img> tag inside the <asp:LinkButton>:
<img src="img/print-icon.png" alt="" runat="server" />

Just a note to add to the solution above.
I found this specifically occuring when I had enabled=false (to show disabled style) my linkbutton and then caused a postback from the page via another control.
The .Text component of the linkbutton got wiped out after postback.
BUT by putting runat="server" on my .Text / html tags (em, span), they now are retained after postback.

the problem is that the Attributes["onclick"] = override the handler of the onclick operation.
2 thing you could try :
LinkButtonPrint.Attributes.Add("onclick", "StartLoadTracking(this, '" + GetLocalResourceObject("Loading") + "');");
or
LinkButtonPrint.Attributes["onclick"] = "StartLoadTracking(this, '" + GetLocalResourceObject("Loading") + "');" + LinkButtonPrint.Attributes["onclick"];

Related

Dynamically set picture src asp.net

is it possible to set the src of a image with a button click.
Each of my buttons represents a picture that should be displaying in my "image" area. I need the image Area's SRC property to be affected by the button click.
Im using visual studio 2012 with c#.
-Edit : Using AJAX Update panel in visual studio 2012 with C#
If a postback is acceptable to you for every image change, you may do something like :
In C#:
protected void btnClick(object sender, EventArgs e) {
Button btn = (Button) sender;
switch (btn.ID) {
case "btn1": img.ImageUrl = "<Image_Url>"; break;
case "btn2": img.ImageUrl = "<Image_Url>"; break;
}
}
In ASPX Page:
<asp:Image ID="img" runat="server" />
<asp:Button ID="btn1" runat="server" OnClick="btnClick" />
<asp:Button ID="btn2" runat="server" OnClick="btnClick" />
Yes. You will be able to accomplish this by using JavaScript and attaching a click handler to the button (onclick="loadImage1()").
loadImage1 function would require you to write the javascript necessary to access the src attribute of the image element and alter it.
You can achieve this with plain javascript (see above concept), or with some javascript library such as jQuery. For cross browser compatibility and to save you from having to write your cross browser safe logic, I would suggest jQuery to handle this.
<img id="img1" src="initialimagehere.jpg"/>
And then you can change the src attribute like this:
$("#img1").attr("src","newimagehere.jpg");
jQuery: this link
I noticed if I had not first specified a value for ImageUrl in my .aspx code, I could not then set it in the .aspx.cs code.
Ie, if I had my .aspx code as:
<asp:Image runat="server" id="imgPickLg0101" class="ImgSzLarge" />
I could not set it in the code behind.
However, if I first specified a value for ImageUrl:
<asp:Image runat="server" id="imgPickLg0101" class="ImgSzLarge" ImageUrl="../Images/somepic.jpg" />
Then I could set it in the .aspx.cs code:
imgPickLg0101.ImageUrl = "../Images/DifferentPicture.jpg";
Inside aspx:
<img id="imagenCabecera" runat="server" />
And inside aspx.vb:
imagenCabecera.Attributes("src") = "url-image.jpg"

asp.net imagebutton new window

I have a Telerik Grid. In that I have the following code in an .aspx page. What I want to happen is that when the user click on the imagebutton control it launches a new window to show that image. Note, I have seen some code which use Postback but they are blocked by popup blockers. The control's image is set via codebehind but that should not matter for this question. Here is my code. Thanks!
<asp:ImageButton ID="prod_image_main" runat="server" AlternateText="Product Main Image"
Height="500PX" Width="540PX" />
Instead of using an asp:ImageButton control why not just use a link? That way you can simply set the target attribute of the link to _blank and have it open in a new window.
Something like this:
<img src="wherevertheimageis.jpg" />
Try to open a new window with a javascript function:
function OpenW() {
window.open('NewForm.aspx', '', "height=200,width=200");
}
And in your imageButton set the onclientclick:
<asp:ImageButton ID="prod_image_main" runat="server" AlternateText="Product Main Image"
Height="500PX" Width="540PX" onclientclick="OpenW()" />
And load the image at the onload of NewForm.
Based on Mike Evan's answer here is what works for me.
ASPX FILE:
<asp:HyperLink runat="server" ID="hpl_mainimg" Target="_blank">
<asp:Image ID="prod_image_main" runat="server" AlternateText="Product Main Image"
Height="500PX" Width="540PX" /> </asp:HyperLink>
Code Behind C#
prod_image_main.ImageUrl = File.Exists(Server.MapPath("images_products/" + rdr["image_1"].ToString())) ? "images_products/" + rdr["image_1"].ToString() : "images_missing/NotAvailable_RS.jpg";
prod_image_main.ToolTip = rdr["itemtitle"].ToString();
hpl_mainimg.NavigateUrl = prod_image_main.ImageUrl.ToString();

Server Control Auto Postback with form has _blank attribute

My case is I have an asp.net page has a form
<form id="form1" runat="server" target="_blank">
and a button redirect to another page and this page will open in a new window because of the target attribute of the form .
<asp:Button ID="button1" runat="server" PostBackUrl="~/kindofpage.aspx" Text="Generate" />
and I have a dropdownlist has auto postback = true to post the past to fill another dropdownlist by selected data .
<asp:dropdownliast id="Make" name="Make" runat="server" autopostback="true"></asp:dropdownlist>
the question is : why when I select item from the auto postbacked dropdown an blank page opened ?
I need a way to post the page by the dropdownlist without openning a blank page ..
Thank you,
For lack of a better idea, you could just remove the target="_blank" attribute from your markup, and when your button is clicked, modify the form tag with JavaScript and set the attribute.
You can set the OnClientClick property and run JavaScript when it's clicked. For example:
<asp:Button ID="button1" OnClientClick="document.getElementById('form1').setAttribute('target', '_blank')" runat="server" PostBackUrl="~/kindofpage.aspx" Text="Generate" />
You could always just adjust your buttonpress code to open a new window such as this:
<asp:Button ID="myBtn" runat="server" Text="Click me"
onclick="myBtn_Click" OnClientClick="window.open('kindofpage.aspx', 'kindofpage');" />
then remove the:
target="_blank"
From the form tag.
I struggled with a similar situation but solved it in the following way.
As mentioned in this answer, you can use the OnClientClick property to set the target to "_blank". E.g.
<asp:Button ID="button1" OnClick="codebehind_method" OnClientClick="document.forms[0].target = '_blank';" runat="server" Text="targets new window" />
Then, in the aspx page that my "codebehind_method" function redirects to, I reset the target of the opener form like so:
<script type="text/javascript">
function resetTarget() {
opener.document.forms[0].target = '';
}
</script>
<body onload="resetTarget()">
Now, if you go back to your opener form and use a control that does not have the "OnClientClick" property set, the AutoPostBack should occur in the same tab.
If you want to find your form by ID, replace "document.forms[0]" with:
document.getElementByID('yourFormName')
<form id="form1" runat="server">

multiple forms in asp.net

is it possible to display, with a click of a button an entirely different form on the same aspx page? please take note that although i have experience with vb.net, i have almost none with asp.net. thank you very much for your responses
I would use and in your code behind, load up the page and then place it in the placeHolder. And then hide the old form using javascript. The idea the other person said would also work, but I like using the placeholder, myself.
I think it's all really determinate on what you want to do with the forms and how badly you would want the code for the other form laying on the page, or not.
If I understand, what you need is, on the click event:
response.redirect "newpage.aspx"
Create each of the forms on the same page, one with visible=true and the other visible=false, and when the user clicks on the appropriate button, switch the visibilities.
<form id="Form1" runat="server" visible="true">
<div>
<asp:Button ID="Button1" runat="server" Text="Show Form 2" onclick="Button1_Click" />
</div>
</form>
<form id="Form2" runat="server" visible="false">
<div>
<asp:Button ID="Button2" runat="server" Text="Show Form 1" onclick="Button2_Click" />
</div>
</form>
And in the code behind:
protected void Button1_Click(object sender, EventArgs e)
{
this.form2.Visible = true;
this.form1.Visible = false;
}
protected void Button2_Click(object sender, EventArgs e)
{
this.form2.Visible = false;
this.form1.Visible = true;
}
Probably not the most "Ajaxy" solution, but you could use an iframe, with the src set to the forms location.
You should be aware of ASP.NET's MultiView control. It does require a postback to change views, and it is kinda heavy on the ViewState, but its an option to consider.
Well, there's several ways to go about that I suppose. Riffing off tekBlues, you can do a Server.Transfer "yourpage.aspx". You can then use the PreviousPage property to get to data from the old page.
You can use user controls and a placeholder on the main page. Of course dynamically loaded controls holds extra complexity.
You could use a MultiView control. Asp.Net will maintain all vars for you. Useful for the quick and dirty.
These are all webform solutions though. If you're looking for an AJAX solution, might need to keep on looking for answers.
It is NOT allowed to have more then 1 form runat="server" on an asp.net page. What you could do, is create 2 panels on your page, 1 with the Visible property set to false. Then when a button is clicked in the event handler you set the Visisble property to true, while setting the other 1 to false. Wrap the Panel in an UpdatePanel to get rid of the postback.
<asp:UpdatePanel><ContentTemplate>
<asp:Panel ID="pnl1" runat="server">
<asp:Button OnClick="Button_CLick" />
</asp:Panel>
<asp:Panel ID="pnl2" runat="server" Visible="false">
</asp:Panel></ContentTemplate></asp:UpdatePanel>
the code in the Button_CLick handler would then be pnl1.Visible = false; pnl2.Visible = true;
You could do it with CSS/Javascript, here is what I would do first:
1) code up two forms, place them in a separate divs
2) using CSS hide one div on page load
3) then place a button on the page, in the onlick button event unhide the second form and hide the first one.
Make sure that you only have ONE form tag, but 2 divs inside it which you will hide/unhide. Keep in Mind that that the form can only be submitted to its own page, that's asp.net.
in your HTML:
<form runat="server" id="myForm">
<div id="myForm1">
<! -- form 1 code goes here -- !>
</div>
<div id="myForm2">
<! -- form 2 code goes here -- !>
</div>
<input type="button" onclick="toggleVisibility();" />
</form>
Then in your CSS
#myForm1 {
display: none;
}
Then ToggleVisibility() will change the display attribute of divs.
Use AJAX to load the content of another page into the same page.
Use Response.Redirect or Server.Transfer to move to the next page.

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