Change Image Url at button click - c#

In my asp.net page I have Image control , in which myimage.png will display at page load. Requirement as below,
Browse image using File upload control and on click of Upload button , immediate preview need to be displayed in Image control. When upload button is pressed after browsing image, the existing "myimage.png" will be deleted and new image will be saved into sever path with same name and preview need to be displayed in image control.
Issue is After saving image , image control is not displaying the new image immediately.
To view the image page need to be re-loaded. Code as below,
In aspx page,
<asp:Image ID="imgLogo" style="margin-left: -299px;" ImageUrl="~/images/myimage.png" runat="server" />
Code behind as below,
protected void btnUpload_Click(object sender, EventArgs e)
{
string filePath = FileUpload1.PostedFile.FileName;
File.Delete(Server.MapPath(#"~\images\myimage.png"));
FileUpload1.SaveAs(Server.MapPath(#"~\images\myimage.png"));
imgLogo.ImageUrl = Server.MapPath(#"~\images\myimage.png");
}
Regards

The reason your page must be reloaded is because ASP.NET code is executed on a server. So every time you, for example, click the button with a server-side code inside, the request is sent to the server, server executes your code and returns a proper response. Basically: something MUST be reloaded. It doesn't have to be the entire page, though. You can force the browser to reload only a certain piece of page using AJAX extensions such as Script Manager and Update Panel.
Example (aspx page):
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Click the button."></asp:Label>
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Hello World" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
OnClick event:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Hello world!";
}
Also, you can force the panel to update it's content using the Update() method of the UpdatePanel.

This looks like a browser caching issue.
The url is exactly the same as it was prior to changing the image file, so the cache will use the originally named file (in its cache) to display.
You can get over this hurdle by adding something extra (but not used) to the url:
protected void btnUpload_Click(object sender, EventArgs e)
{
// Do your upload stuff here...
imgLogo.ImageUrl = "~/images/myimage.png?" + DateTime.Now;
}

Related

Adding OnClick event to ASP.NET control

i would like to create OnClick event for my panel. So far now the most of the google results look more or less like this: adding onclick event to aspnet label. Is there any way, to call codebehind function from javascript or panel attributes? Because I would like to Redirect user to a new page and before that save some information in ViewSTate or Sessionstate. Any suggestions?
In your java script method raise a __dopostback call to a Server side method.
<script type="text/javascript">
function YourFunction()
{
__doPostBack('btnTemp', '')
}
</script>
Where btnTemp is a server side button, so write a onClick event of this button on server side, where you can do the processing and then redirect to other page.
You can have a good understanding of dopostback at DoPostBack Understanding
My aspx page is like:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<script type="text/javascript">
function CallMe() { __doPostBack('btnTemp', '') }
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="btnTemp" runat="server" Text="Test" onclick="btnTemp_Click" />
<div> <asp:Label ID="Label1" runat="server" Text="Label1"></asp:Label>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label></div>
</form>
</body>
And my Server Side code is as:
protected void Page_Load(object sender, EventArgs e)
{
Label1.Attributes.Add("onClick", "CallMe();");
}
protected void btnTemp_Click(object sender, EventArgs e)
{
}
Thats the code that I have written, I haven;t included the using statement, Page directive etc in above code.
There is a PostBackUrl property on a ASP.NET Button, you could render the button as normal then postback to a different page - this is where your OnClick method would need to be declared.
I would strongly recommend against posting back to the same page then doing a Response.Redirect(), consider the traffic. The browser requests the page, posts back then is sent a HttpRedirect and then navigates to the new page. With the method I have outlined above this is not required and the browser has to make one request less (meaning the message doesn't have to be sent or the page rebuilt on the server) and is a significant performance benefit.

Why IE does not refresh the page after a JS call to a click button?

On a ASP.Net page, I am in front of a problem only with IE. Here is the description.
On a page, there is two buttons and one label. The first button is visible and calls a JS function on the click event. This JS function calls the click function of the second button. The second button has an C€ event handler on the click event. The C# event handler edit the label.
In Firefox : the label is correctly edited after the clicks.
In IE (8) : the label is not edited, despite the C€ event handler has been correctly hit.
Also, I observed, in IE, that the Page_Load event is called two times after the JS button click :
Page_Load
button2_OnClick => change of the Label Text
Page_Load => The Label Text is reset :(
In Firefox, the Page_Load is called only once.
My question is : how to make IE refresh correctly the page as Firefox does after a JS button click ?
Below is the sample test code :
1) Page ASPX
<head runat="server">
<title></title>
<script type="text/javascript">
function button1Click(sender, args) {
var button2 = document.getElementById("button2");
button2.click();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button runat="server" ID="button1" Text="Click-me!" OnClientClick="button1Click();" />
<asp:Button runat="server" ID="button2" Text="Second" OnClick="button2_OnClick" style="display:none" />
<p />
<asp:Label runat="server" ID="label1" Text="Init" />
</div>
</form>
</body>
</html>
2) C# code-behind :
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void button2_OnClick(object sender, EventArgs e)
{
label1.Text = "Changed";
}
}
The ID of your button will not be button1 or button2 when it's rendered. It will probably be something like ctl001_button1. Therefore your javascript will not work. In ASP.NET 4 you can override this behaviour by using an assigned ClientID.
<asp:Button runat="server" ID="button1" Text="Click-me!"
OnClientClick="button1Click();" ClientIDMode="Static" />
<asp:Button runat="server" ID="button2" Text="Second"
OnClick="button2_OnClick" style="display:none" ClientIDMode="Static" />
As an aside, this alludes to the main problem with ASP.NET Winforms - it tricks developers into thinking that the web is a connected environment.
What actually happens when you click an <asp:Button /> element by default is that a postback is invoked. I.e. Your browser sends a request to the server for a new page. It sends up something called ViewState which is how the server knows what you've done and what to render. There is no "event" handled as such.
I think the problem is with the way you are trying to get the hidden button
var button2 = document.getElementById("button2");
maybe change this to
var button2 = document.getElementById("<%= button2.ClientID %>");
After the buttons are rendered in the browser, the ID is changed by the ASP.Net engine, and not the same as your source.
http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientid.aspx
Hope this helps.

How to hide/show a control using AJAX (AjaxControlToolkit) and C#

I know this must sound really basic but I'm really stumped here. What I'm trying to do is to show a Hyperlink once a process has completed. And this process is the AsyncFileUpload. In the ASPX page, I want to create an but have it hidden on the initial page load. If I set the Style="display: none;" seems to work but after the file upload, nothing I do, will make the control visible again. When the file is uploaded, it calls a function called FileUploadComplete. It's in here that no matter what I do, the Hyperlink won't display.
Any help is greatly appreciated :)
Thank you,
dave
Here is the ASPX Code (with recently added javascript)
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="OptionsPlaceHolder" runat="server">
<script language="javascript" type="text/javascript">
function ShowLink() {
$("#openFile").show();
}
</script>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolderBody" runat="server">
<asp:UpdatePanel ID="updImportFile" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div class="pageHeader">
<asp:Literal runat="server" ID="pageTitle" Text="<%$ Resources:Resources, ImportFile %>" />
</div>
<ajaxToolkit:AsyncFileUpload ID="FileUpload1" runat="server" Width="600px"
UploaderStyle="Traditional" OnUploadedComplete="FileUploadComplete" ThrobberID="throbber"
CompleteBackColor="#E9F2FD" OnClientUploadComplete="ShowLink" />
<asp:Image runat="server" ID="throbber" ImageUrl="images/loading.gif" />
<br />
<asp:Hyperlink runat="server" ID="openFile" NavigateUrl="~/OpenFile.aspx" Text="Open"
style="display:none;"/>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
And here is the code behind:
protected void FileUploadComplete(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string importName = Server.MapPath(#"Uploads\") + FileUpload1.FileName;
FileUpload1.SaveAs(importName);
// Import the JSA
JSA jsa = new JSA();
jsa.Import(importName);
// Show the Hyperlink
ShowLink();
}
}
private void ShowLink()
{
openFile.Attributes["Style"] = string.Empty;
}
I didn't include the master page code. It has the ToolkitScriptManager in it.
Are you trying to show on client-side or server-side? Is the link a client-side, or server-side object? Javascript would be the standard way.
If the control is a client-side object:
document.getElementById("hyperlink_name").style.display = "block";
Or if it is a server-side object:
document.getElementById("<%= hyperlink_name.ClientID %>").style.display = "block";
I would recommend getting jQuery and using the following though:
$('#hyperlink_name').show();
Or you can use an ASP.Net Link Button and do it server-side:
linkButton.Visible = true;
It would be more helpful if you would post some of the code you have tried already so that we can get a better idea of where you are.
{first answer deleted}
[EDIT :I didn't catch that you are using AsyncFileUpload when I first read the question]
Using AsyncFileUpload inside an update panel the server is being accessed via a partial postback, as a result other controls (the hyperlink) cannot be affected on the server. This will require that you make use of javascript (or preferably jquery) to make the change on the client.
You can do it on OnClientUploadComplete function, but you have to reference the hyperlink like this: <%= hyperLink.ClientID %>.style.display = 'block';
Another more asp.net way is to use update panels. Put the hyperlink into an UpdatePanel and set a trigger on the UpdatePanel when the file is uploaded. then change the visibility on the server at UploadedComplete event.

change masterpage image src from page in update panel C#

I have a master page that contains an image as follow:
<asp:Image ID="imgCompanyLogo" runat="server" ImageUrl="image path" />
and in a child page I want to edit the property ImageUrl as follow:
Image imgCompanyLogo = (Image)Page.Master.FindControl("imgCompanyLogo");
imgCompanyLogo.ImageUrl = ResolveUrl("~/images/CompanyLogo/Logo.png");
and it doesn't give me an exception, but it doesn't change anything.
Note: I have an UpdatePanel in the child page.
Since the image is sitting outside of the UpdatePanel, server side changes will not be executed on the image after a partial postback. Your only option is to inject JavaScript into the page and change the image URL.
Use the ScriptManager.RegisterStartupScript Method to inject JavaScript after the partial postback.
Something like the following will work for you:
C#
protected void btnPostback_Click(object sender, EventArgs e)
{
imgCompanyLogo.ImageUrl = ResolveUrl("~/images/CompanyLogo/Logo.png");
ScriptManager.RegisterStartupScript(btnPostback,this.GetType(), "myScript", "ChangeImage('" + ImageUrl + "');",false);
}
JavaScript
function ChangeImage(imgURL) {
//make sure the ID of the image is set correctly
document.getElementById('imgCompanyLogo').src = imgURL;
}
Wrap image by UpdatePanel with UpdateMode="Always"
Master Page:
<asp:UpdatePanel runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:Image runat="server" ID="Image1" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:ContentPlaceHolder ID="MainContent" runat="server">
</asp:ContentPlaceHolder>
public void SetImageUrl(string url)
{
Image1.ImageUrl = url;
}
Child Page:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Button Text="Click Me" runat="server" OnClick="UpdateImage" />
</ContentTemplate>
</asp:UpdatePanel>
protected void UpdateImage(object sender, EventArgs e)
{
((Main)Master).SetImageUrl("~/Images/0306d95.jpg");
}
The code above works well for me.
Have a look at Sys.WebForms.PageRequestManager Class. Define handler in javascript and may change the image source.
If your code is being run after an async postback (per your UpdatePanel) then changes to anything outside the UpdatePanel will not be rendered. Content in the master page would definitely seem to qualify.
If this is what you're trying to do, this model won't really work. You will need to use some client script to effect changes to already-rendered content when working with this model.
An UpdatePanel is a construct to identify an area that's updated through ajax. The page is not actually reloaded. So an postback can never change content that's outside of the UpdatePanel (or control bound to that panel) that sourced it.
Here's a basic implementation (using jQuery). Add a hidden field to pass the new source to the client. This must be inside the UpdatePanel. Change this value from the server when you want the image to update with new_image_src.Value=ResolveUrl(...);
<asp:HiddenField ClientIdMode="Static" runat="server" id="new_image_src"
value="" EnableViewState="false">
Give your image a static id too to make life easier:
<asp:Image ClientIdMode="Static" runat="server" id="dynamic_image" ImageUrl="..." >
Add javascript to the page (should NOT be in the UpdatePanel):
function updateImage() {
var new_src=$('#new_image_src');
if (new_src) {
$('#dynamic_image').attr('src',new_src);
/// erase it - so it won't try to update on subsequent refreshes
new_src.val('');
}
}
$(document).ready(function() {
/// adds an event handler after page is refreshed from asp.net
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(updateImage);
});
This wouldn't be difficult to do without jquery either but seems more common than not these days.

Setting focus onto another contol from button click

I am using ASP.NET 2.0 and VB.NET (C# code will also help me out)
On top of my page I have a button called btnViewRecords. When the User click on the button I want to set focus to another button or label further down on the same page. How can this be done.
This code does not work for me..............
btnTheRecords.Focus()
or
lblHeader.Focus()
Thanks in advance!!
Edit:
Even if my code did work, i dont want to reload the page every time.
Here's a relatively simple solution...
<asp:Button ID="Button1" runat="server" Text="Button"
OnClientClick="return SetFocus()" />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<script type="text/javascript">
function SetFocus() {
document.getElementById('<%=TextBox2.ClientID %>').focus();
//or this if you're using jQuery
//$("#<%=TextBox2.ClientID %>").focus();
return false;
}
</script>
You can use JavaScript to do this.
document.getElementById ( "btnTheRecords" ).focus();
By setting focus what do you mean. Do you want to bring this control into view if it is way down the page. Then there are better ways to do this.
Edit:
You can place an anchor tag near the button or the bale and set
location.href = "#anchorId";
where anchorId is the id of the anchor tag.
will move the focus to the anchor tag.
Try this,
I wrote a small code and it seems to be working for me. sorry this is in C# but if you click on a button and set focus on another button then page will automatically scroll down for you.
ASP.NET
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
<div style="height:50px;"></div>
<div>
<asp:Button ID="Button1" runat="server" Text="Button 1" onclick="Button1_Click" />
</div>
<div style="height:1000px;"></div>
<div>
<asp:Button ID="Button2" runat="server" Text="Button 2" onclick="Button2_Click" />
</div>
</form>
</body>
</html>
AND Code Behind
using System;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Button2.Focus();
Label1.Text = "button1 clicked & button2 in focus";
}
protected void Button2_Click(object sender, EventArgs e)
{
Button1.Focus();
Label1.Text = "button2 clicked & button1 in Focus";
}
}
I'm not sure exactly of the problem you're having. But in cases where the SetFocus() function and such just don't work (and they often don't in VB for some reason). I've often used workarounds such as shortcut Keys & mnemonics in combination with SendKeys() to get focus where I need it to be.
Depending on whether the buttons you are talking about are in your ASP.NET code or in your VB.NET code, this may be a viable workaround for you as well.
document.getElementById("spanId").scrollIntoView(false)
Reference:
.scrollIntoView
If the button is server side, set the "OnClientClick"
action on it to a javascript function. Cancel windows
events so the page location does not change.
function goto(){
window.event.cancelBubble = true;
window.event.returnValue = false;
document.getElementById("pageloction").focus()
}
asp:Button runat="server" ID="btnTheRecords" OnClientClick="javascript:goto()" />
span id="pageloction">

Categories

Resources