Get File ID in page after upload file by AsyncFileUpload(ajaxToolkit) - asp.net

I am using AsyncFileUpload (ajaxToolkit) control for uploading image file from registration page. uploaded file content are store into DB. So I need to show my uploaded file in asp:image control by httphander like <asp:image id="imgLogo" runat="server" ImageUrl="Images.aspx/id=12" />. So how to do this.

Assuming you are storing the image as a byte[] in DB;
var data = new byte[1]; //Replace this with your values from DB
var mimeType = "application\pdf"; //Replace this with your values from DB
response.ContentType = mimeType ;
response.BinaryWrite(data);
This code should be placed in page_load in images.aspx after you have retrieved the values from the DB.

Your image page handler page_load method will be
Images.aspx
protected void Page_Load(sender s, eventagrs e){
var imagecontent= new byte[XXXX]; // Read DB content as bytes for the passed Id
response.ContentType = 'jpeg/gif/anything' ;
//this should be a valid MIME type saved in database
response.BinaryWrite(imagecontent);
}
Edit:
From your comments you are trying to update the image tag src value
from codebehind using Asp.Net Ajax.
If you want to do this, first make sure your page has access to view state
information about those image tags. This is not a big deal, you simply
wrap the image tags container panel/div with update panel.
So your ajax request will send the information about those viewstate and
push the partial update for those image container panel also.

I have reviewed many site and I got answer of this question..
http://www.mikeborozdin.com/post/AJAX-File-Upload-in-ASPNET-with-the-AsyncFileUpload-Control.aspx
<ajaxToolkit:AsyncFileUpload ID="afuCompanyLogo" runat="server"
OnClientUploadError="uploadError" OnClientUploadComplete="uploadComplete"
UploaderStyle="Modern" UploadingBackColor="#CCFFFF"
ThrobberID="myThrobber"
onuploadedcomplete="afuCompanyLogo_UploadedComplete" />
<asp:Image ID="imgCompanylogo" CssClass="imgCompanylogo" runat="server" Height="80px" Width="80px" AlternateText="" />
protected void afuCompanyLogo_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
if(afuCompanyLogo.HasFile)
{
FileManagementEntity fileManagementEntity = new FileManagementEntity();
FileManagement fileManagement = fileManagementEntity.Create();
fileManagement.FileContentType = afuCompanyLogo.ContentType;
fileManagement.FileContent = afuCompanyLogo.FileBytes;
fileManagement.Size = afuCompanyLogo.FileBytes.Count();
fileManagement.OriginalName = afuCompanyLogo.FileName;
fileManagementEntity.Save(fileManagement);
ViewState["logoID"] = fileManagement.FileManagementID;
imgCompanylogo.ImageUrl = "Image.aspx?id=" + fileManagement.FileManagementID.ToString();
ScriptManager.RegisterClientScriptBlock(afuCompanyLogo, afuCompanyLogo.GetType(), "img", "top.document.getElementById('" + imgCompanylogo.ClientID + "').src='Image.aspx?id=" + fileManagement.FileManagementID + "';", true);
}
}

Related

What is the life cycle of an ASP button?

I'm having an issue with the cycle of a page reload and I can't figure it out. I have an ASP button the runs at the server but it has an associated client side click. The client side Javascript is running correctly and returning true to the button click so it is also running. The Javascript makes a modification to the query string on the URL and this is also working. However, in the C# code behind, the query string is not there. Somewhere, I'm missing something.
The HTML link:
<asp:Button ID="btnRunMOReport" class="button-dbg" runat="server"
Text="Run MO Report" OnClick="btnMO_Report_Click"
OnClientClick="return validateCheckBoxesMO()" />
The JavaScript portion:
function validateCheckBoxesMO() {
token='xyz';
let url1 = window.location.href;
if (url1.indexOf("?") > 0) {
url1 = url1.substring(0, url.indexOf("?"));
}
url1 += "?hiddenToken=" + token;
window.location.replace(url1);
return true;
}
The hiddenToken is now represented on the page (?hiddenToken=xyz).
The code behind:
protected void btnMO_Report_Click(object sender, EventArgs e)
{
MailMessage mailtest = new MailMessage();
mailtest.IsBodyHtml = true;
SmtpClient SmtpServertest = new SmtpClient(ConfigurationManager.AppSettings["smtp_server"]);
mailtest.To.Add("Whoever#test123.com");
mailtest.From = new MailAddress("Whoever#test123.com");
mailtest.Subject = Request.QueryString["hiddenToken"];
mailtest.Body = "Whatever";
}
The mail comes just fine but the subject is blank. Somehow, during the page reload cycle, the query string has not yet been set.
If there is a better way to pass data from the JavaScript to the code behind, I'm all ears.
I want to launch another page from the code behind but I need some data that is returned from the JS. The token is actually something I fetch, process the JSON and now I want to make that token available to the code behind for additional information to add to the new URL I am constructing. Probably TMI for this but it is what I am trying to do.
Thanks for your assistance.
Your script isn't working because the browser makes a POST request to submit the form (and __VIEWSTATE) using the action="" attribute of the <form> that WebForms adds to your page.
When your client-script sets window.location it isn't changing how the <form> will behave. You could use your script to append the new querystring value to the <form>'s action="" attribute and this may work, however it will likely fail if the application has request-validation enabled (in which case ASP.NET will reject a tampered form submission).
As you're using WebForms (and you shouldn't be using WebForms in 2021...) you shouldn't try to fight it unless you understand how it all works (I'm not trying to be condescending: it took me years to figure it all out and I've been using WebForms since 2004).
Instead, provide the value through an <asp:HiddenField>:
Change your .aspx markup to this:
<asp:Button runat="server" ID="btnRunMOReport" class="button-dbg"
Text="Run MO Report" OnClick="btnMO_Report_Click"
OnClientClick="return validateCheckBoxesMO()" />
<asp:HiddenField runat="server" ID="superSecretHiddenField" />
Change your client script to this:
function validateCheckBoxesMO() {
const hiddenFieldId = '<%= this.superSecretHiddenField.ClientID %>';
const hiddenField = document.getElementById( hiddenFieldId );
token='xyz';
hiddenField.value = token;
return true; // <-- This is wrong, btw. Instead use `Event.prototype.stopPropagation()` - but that requires the on-click function to be wired-up correctly and I don't remember the specifics other than that WebForms *doesn't* do things correctly (not out-of-spite, but because WebForms predates the standardisation of client-script events).
}
And your code-behind to this:
protected void btnMO_Report_Click(object sender, EventArgs e)
{
MailMessage mailtest = new MailMessage();
mailtest.IsBodyHtml = true;
SmtpClient SmtpServertest = new SmtpClient(ConfigurationManager.AppSettings["smtp_server"]);
mailtest.To.Add("Whoever#test123.com");
mailtest.From = new MailAddress("Whoever#test123.com");
mailtest.Subject = this.superSecretHiddenField.Value;
mailtest.Body = "Whatever";
}
As noted, a button post back will in general over-write the url that you change. Unless you actually do a navigation client side that is caused by the js, then it will not persist.
So, on the most simple level, just drop in a text box, or hidden field, and put the value you need/want into that hidden textbox or field.
So, client side? Markup?
You can use this:
<asp:Button ID="Button1" runat="server" Text="Delete"
OnClientClick="SetHidden();"/>
<asp:HiddenField ID="HiddenField1" runat="server" ClientIDMode="Static"/>
<br />
<script>
function SetHidden() {
hField = document.getElementById('HiddenField1');
hField.value = 'zoo';
return true;
}
</script>
So in above, we set our value in js to zoo, and of course we do return true. If we return false then the asp.net button code server side will not run - so we can control this, or even say pop up a confirm dialog and return true/false based on that to control if the server side code behind will run.
Server side, code behind? You can now use this:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Debug.Print(HiddenField1.Value)
End Sub
So the above is easy, clean. You can also use a text box, and set the style="display:none", but a hidden field is just as well and easy.

Passing data from a aspx page to a aspx popup

Following is the scenario I am facing, I have a aspx page in which I have added my ascx user control, I also have a <a href control which call a js function to open a aspx popup.
when I open the popup, I need to send the data present in the ascx control to my popup. can you please guide me what method can I use to achieve this other than using session, as the data can be updated in many different places hence maintaining in session will be difficult.
Thanks
try with these syntaxe ( RegisterStartupScript + window.open)
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "newWindow", "window.open('Test.aspx?ID=" + _cId + "','_blank','status=1,toolbar=0,menubar=0,location=1,scrollbars=1,resizable=1,width=30,height=30);", false);
You said that you are using a js function to open the aspx popup.
then it is simple.
1. Read the Data from the controls of the User control by using javascript
var variable1 = document.getElementByID("ControlId").value;
var variable2 = document.getElementByID("ControlId").value;
2. Pass this data as query string to the next page
window.open("http://www.w3schools.com?id=" + variable1 + "&name=" + variable2);
You can read this data from querystring from the next page
If you cant sent data as querystring , can try some other ways
1. Try to post the form to the other page using target="_blank".
we can dynamically change the form action if needed.
OR
2. Make use of the window.opener object from the popup to read the data from controls the opener page.
var variable1 = window.opener.getElementById("ControlId").value
Create a hidden variable in your ascx.
<asp:HiddenField runat="server" ID="hdnId" />
On page load of ascx set the value to be sent to the hidden variable
protected void Page_Load(object sender, EventArgs e){
hdnId.Value = <value to be sent to pop-up>;
}
Register a ajax manager in the code behind.
protected override void OnInit(EventArgs e)
{
RadAjaxManager.GetCurrent(this.Page).ClientEvents.OnRequestStart = "ajaxMngr_RequestStart;";
base.OnInit(e);
}
In the ajaxMngr_RequestStart() JS
function ajaxMngr_SA_RequestStart(sender, args) {
var oPatId = "<%=hdnSendPatId.Value %>";
//add code to open the pop-up, add oPatId as part of the URL
}
}
I use Telerik, which makes helps a lot in managing pop-ups. Let me know, if this helps.
Cheers!

Update an image control as soon as a file is selected in File Upload control in ASP.NET

I have an image control and a file upload control in .NET 2.0 (VS.NET 2008) form. As soon as user selects an image file in the file upload control, i want the image to appear in the image control of the form. What would be the way to do this ?
(The only event File Upload seems to support is 'OnChange' and i don't know enough javascript to update Image1.URL based on content of FileUpload).
Thanks,
Chak.
You need to upload Asynchronously , and you could try AJAX AsyncFileUpload and this is what you are looking...
http://asp.net-informations.com/ajax/ajax-AsyncFileUpload.htm
Are you looking for a kind of preview? You can only show the image to the user after the file has been uploaded. I'm pretty sure the user has to actively do so (otherwise you could try to read the entire filesystem from the browser)
I think this is a good example:
http://www.codeproject.com/KB/ajax/AJAXUpload.aspx
this is a good starting point too:
http://www.eggheadcafe.com/community/aspnet/2/10204276/how-to-display-image-when-upload-image.aspx
or here:
http://www.eggheadcafe.com/community/aspnet/2/10236947/image-upload-and-display.aspx
updated
protected void Button4_Click(object sender, EventArgs e)
{
string strExtn;
string strpostedfile;
strpostedfile = fileuploading.PostedFile.FileName;
strExtn = System.IO.Path.GetExtension(strpostedfile);
strExtn = strExtn.ToLower();
string strEx = Path.GetExtension(fileuploading.PostedFile.FileName).ToLower();
String filename = Path.GetFileName(fileuploading.FileName);
filename = filename.Remove(filename.Length - strEx.Length);
fileuploading.SaveAs(Server.MapPath("~/Photos/") + filename);
uploadImage.ImageUrl = "~/Photos/" + filename;
}
Page:
<asp:FileUpload ID="fileuploading" runat="server" />
<asp:Button ID="Button4" runat="server" onclick="Button4_Click" Text="Button" />
<br />
<asp:Image ID="uploadImage" runat="server" />

How to place a hyperlink field in a web page at runtime?

I am trying to display contents of a folder in a hyperlink. I am using masterpage also. The hyperlinks are not shown into the content page. what to do for that?
I know in windows forms we can use like
TextBox.Location=new Point(100,100);
But how to do in web page...please anybody suggest me..
my coding in page_load is
protected void Page_Load(object sender, EventArgs e)
{
DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/ProjectsUpload"));
int i = 0;
foreach (FileInfo fi in di.GetFiles())
{
HyperLink HL = new HyperLink();
HL.ID = "HyperLink" + i++;
HL.Text = fi.Name;
HL.NavigateUrl = "downloading.aspx?file=" + fi.Name;
Page.Controls.Add(HL);
Page.Controls.Add(new LiteralControl("<br/>"));
}
}
You can't add it directly to Page.Controls. You have to add it to the ContentPlaceHolder on the page.
Instead of dynamically creating controls, which is rather messy and error-prone, have you considered using an asp:Repeater control and binding the files directly to it? Something like:
<asp:Repeater ID="RepeaterFiles" runat="server">
<ItemTemplate>
<asp:HyperLink runat="server" Text='<%# Container.DataItem %>'
NavigateUrl='<%# String.Format("downloading.aspx?file={0}", Container.DataItem)%>' />
<br />
</ItemTemplate>
</asp:Repeater>
and in code behind:
DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/ProjectsUpload"));
RepeaterFiles.DataSource = di.GetFiles();
RepeaterFiles.DataBind();
That way you can use declarative mark-up to control layout and keep the logic in your code-behind.
Put a PlaceHolder control on your page:
<asp:PlaceHolder runat="server" ID="ph" />
In your code behind write like:
HyperLink HL = new HyperLink();
HL.ID = "HyperLink" + i++;
HL.Text = fi.Name;
HL.NavigateUrl = "downloading.aspx?file=" + fi.Name;
ph.Controls.Add(HL);
ph.Controls.Add(new Literal { Text = "<br/>"});
I'm making use of the newly C# 3 feature on that last line to set the Text property.
Have you used the debugger to step through the loop to verify that it processes at least one file?
Instead of adding the links to Page.Controls, you could put a list control on the page, and then add each link within a list item. Then you'd know precisely where on the page they should appear.
Create a Panel or a Label in the Page's Content area, and add your HyperLinks into the Controls collection of the Panel.
(Stepping through the code to check whether the IIS App actually enumerates any files in the directory would help too.)

How to locate the theme folder in Asp.net?

I'm binding some image controls dynamically but don't set image URL. When I use a skin file and then set the SkinId, I get the following error:
The 'SkinId' property can only be set in or before the Page_PreInit event for static controls. For dynamic controls, set the property before adding it to the Controls collection.
How do I get a virtual theme's location?
Set the SkinId on the markup
<asp:Image runat="server" id="LogoImage" SkinId="LogoImage" />
To set it programatically you need to set it up on the PreInit event
public void Page_PreInit(object sender, EventArgs e)
{
LogoImage.SkinID = "LogoImage";
}
And here is a blog post for setting the SkinId Programatically
http://blogs.conchango.com/simonevans/archive/2005/06/09/How-to-programmatically-assign-a-SkinID-to-a-control-while-using-a-master-page-in-ASP.net-2.0.aspx
Finally, if you are just looking for the folder, it depends on whether you are using a Theme or a StylesheetTheme.
var path = "~/App_Themes/" + Page.Theme + "/images";
var path = "~/App_Themes/" + Page.StylesheetTheme + "/images";
Update
If you doing this in a Grid use a custom binding method
<asp:Image runat="server" id="myImage" ImageUrl='<%# GetThemedImage(((Product)Container.DataItem).Image)%>' />
then in the code-behind
public string GetThemedImage(string image)
{
return "~/App_Themes/" + Page.Theme + "/images/" + image;
}

Resources