Recently I have been developing web form application in ASP.NET (c#):
I have an Image control:
<asp:Image ID="Avatar" runat="server" Height="225px" ImageUrl="~/Images/NoUser.jpg" Width="225px" />
And FileUpload & Button control
<asp:FileUpload ID="avatarUpload" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" />
When user click button then "Upload" code is executed (the image is sent to the database). Problem is that I like to display the image which the user selected in Avatar Image controller before the user clicks "desperate" button.
Is that possible to do this automatically?
With the help of File Api of HTML5 (Example: Using files from web applications) you can accomplish this easily. Change the markup to use input type="file" instead of asp:FileUpload and add ID, add tag runat="server" to make it accessible from server. Your markup should look like:
<input ID="avatarUpload" type="file" name="file" onchange="previewFile()" runat="server" />
<%--<asp:FileUpload ID="avatarUpload" runat="server" />--%>
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" />
<asp:Image ID="Avatar" runat="server" Height="225px" ImageUrl="~/Images/NoUser.jpg" Width="225px" />
Now add a javascript function previewFile in the head of document:
<head runat="server">
<title></title>
<script type="text/javascript">
function previewFile() {
var preview = document.querySelector('#<%=Avatar.ClientID %>');
var file = document.querySelector('#<%=avatarUpload.ClientID %>').files[0];
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
}
}
</script>
</head>
Now after selecting an image you can see the preview like below:
You can use css to re-size it to a thumbnail.
After clicking the Upload button, in the code you can find the posted file:
protected void Upload(object sender, EventArgs e)
{
int contentLength = avatarUpload.PostedFile.ContentLength;//You may need it for validation
string contentType = avatarUpload.PostedFile.ContentType;//You may need it for validation
string fileName = avatarUpload.PostedFile.FileName;
avatarUpload.PostedFile.SaveAs(#"c:\test.tmp");//Or code to save in the DataBase.
}
Related
i need to request file from fileupload that is created in html. my question is quite simple how do i do this?
i know there is this option : HttpPostedFile File = Request.Files["imagem"]; but when i try to do that my File returns NULL.
I dont know what am i doing wrong, but even this simple code example is not working and i dont know why .
<body>
<form id="form1" runat="server">
<div>
protected void Button1_Click(object sender, EventArgs e)
{
HttpPostedFile File = Request.Files["imagem"];
if ( File != null)
Response.Write("Sucesso");
}
</form>
</body>
and here is my aspx code example :
<input type="file" name="image" class="image-upload" /></div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
can any one explain what am i doing wrong ? thank you
Might just be a typo on here, but change your imagem to image
protected void Button1_Click(object sender, EventArgs e)
{
HttpPostedFile File = Request.Files["image"];
if ( File != null)
Response.Write("Sucesso");
}
In your aspx page you need to tell the form that it will be using files. I don't think its required but its good practice to also include an id in your input that matches your name.
<body>
<form id="form1" runat="server" method="post" enctype="multipart/form-data">
<input type="file" id="image" name="image" class="image-upload" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
</body>
I'd recommend going with the asp.net file upload control:
<asp:FileUpload ID="pictureUpload" class="form-control input-sm input-spacing" runat="server" />
You can create these dynamically
FileUpload OneUpload = new FileUpload();
OneUpload.ID = "Upload" + MyIdNumber;
UploadsDiv.Controls.Add(OneUpload);
Then to access the file, you have:
pictureUpload.SaveAs(FilePathAndName);
You can also access different properties of the posted file...
pictureUpload.PostedFile.FileName
pictureUpload.PostedFile.ContentLength
pictureUpload.PostedFile.ContentType
Here is ASP.NET code:
<div class="row1" style="padding: 3px">
<asp:Button Text="Select" ID="btnDescColumn" runat="server" OnClick="SetDescPoint" CausesValidation="False"/>
<input type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" id="fileSelect" runat="server" class="hidden" />
<asp:Button ID="btnUpload" runat="server" Text="Load" OnClick="LoadFile" class="hidden" CausesValidation="False" />
<input type="button" id="triggerUpload" name="name" value="Select File" />
</div>
Here the view:
Here is JQuery code:
$('#triggerUpload').click(function () {
$('#<%=fileSelect.ClientID%>').trigger('click');
});
$('#<%=fileSelect.ClientID%>').change(function () {
$('#<%=btnUpload.ClientID%>').trigger('click');
});
When Select File button clicked dialog window opens and user select file.
After the file selected, this JQuery code fired:
$('#<%=fileSelect.ClientID%>').change(function () {
$('#<%=btnUpload.ClientID%>').trigger('click');
});
and the JQuery row above trigger this asp button control:
<asp:Button ID="btnUpload" runat="server" Text="Load" OnClick="LoadFile" class="hidden" CausesValidation="False" />
which is fire this code behind method:
protected void LoadFile(object sender, EventArgs e)
{
HttpPostedFile file = Request.Files[fileSelect.Name];
int fileSize = file.ContentLength;
byte[] fileByteArray = new byte[fileSize];
file.InputStream.Read(fileByteArray, 0, fileSize);
}
After the postBack Process button clicked and this code behind is fired:
protected void SetDescPoint(object sender, EventArgs e)
{
if(fileSelect.Value != string.Empty)
{
//make some process...
}
}
But the fileSelect control is empty.
As I understand input file not keep the file between postback calls.
I need to access the file in SetDescPoint code behind.
Any idea how can I keep file between postback calls?
When you uploading a file in asp.net .. you must do a full post-back .. which can only achieve by submitting the page (button click).. no jquery trick will work .. even if your postback button is under a updatepanel .. then also you will not get the physical file in server side
What I have is an ASP.NET 2.0 web application that allows the user to upload a .CSV
The html input type is submit.
I want to know if there is a way I can update my UpdatePanel that is below the input to show a little "Processing" .gif before my onserverclick method takes place.
I have tried putting a reference to another event at the beginning of that event, as well as other methods, but I'm getting no luck. From what I understand the method needs to finish before my UpdatePanel will refresh.
Here is some code for you guys
<div class=" content-div">
<input type="file" id="File1" name="File1" runat="server" />
Select file Type:
<asp:DropDownList ID="ddlfileupload" runat="server">
<asp:ListItem>CSV</asp:ListItem>
</asp:DropDownList>
</div>
<div class=" content-div">
<input type="submit" id="Submit1" value="Upload File" runat="server" onserverclick="Submit1_ServerClick"
style="border-top-style: groove; border-right-style: groove; border-left-style: groove;
border-bottom-style: groove" />
<asp:Label ID="Label6" runat="server" BorderColor="White" BorderStyle="None" Font-Bold="True"
Visible="False"></asp:Label>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
and the event behind the code:
protected void Submit1_ServerClick(object sender, EventArgs e)
{
AddProcessGif();
// Logic from submit button here that uploads .csv
}
AddProcessGif() is a method that programatically adds my .gif and stuff. And it works, I have seen it fire, but only after my upload finishes, which defeats the purpose.
I don't have a very well written application here and I'm pretty new to ASP.NET, so I am not sure how to effectively make a progress bar or anything like it.
Any advice would be appreciated
You can call a c# server side method from javascript.
what you need to do is add a scriptmanaget in your aspx page and set EnablePageMethods to true.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
also your C# method has to be a [WebMethod] like
[WebMethod]
public static string DoSomething(string str1, string str2)
{
string result = "This is concatenation of " + str1 + " and " + str2 + "'.";
return result;
}
and then add the javascript function in your aspx page to call C# server side DoSomething method
<head runat="server">
<title></title>
<script type="text/javascript">
function DoSomthing() {
var str1 = document.getElementById('<%=txtstr1.ClientID %>').value;
var str2 = document.getElementById('<%=txtstr2.ClientID %>').value;
//Here we call server side methode
PageMethods.DoSomeThing(str1, str2, onSucess, onError);
function onSucess(result) {
alert(result);
}
function onError(result) {
alert('Something wrong.');
}
}
</script>
Hope it helps
I have a modal popup extender and a panel inside of an update panel. I do have a Close button which I bind with the CancelControlId. I however, would like to be able to click outside of my modal/panel to close the panel. (instead of using the close button).
I tried a couple things and a plugin clickoutside. Nothing seems to help. Any help or advice is much appreciated. Thanks.
<asp:Content ID="Content3" ContentPlaceHolderID="rightNavigation" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div id="mls_title" class="MLS_Title">
<asp:Label ID="lblTitle1" Text="Tasks" runat="server" class="MLS_titleLbl" /><br />
</div>
<asp:UpdatePanel ID="pnlMap" runat="server">
<ContentTemplate>
<div>
<asp:Button ID="btnMap" runat="server" Text="MAP" CausesValidation="false" CssClass="btnMap" />
<ajax:ModalPopupExtender
ID="ModalPopupExtender1"
runat="server"
TargetControlID="btnMap"
PopupControlID="panel1"
PopupDragHandleControlID="PopupHeader"
Drag="true"
BackgroundCssClass="ModalPopupBG">
</ajax:ModalPopupExtender>
<asp:Panel ID="panel1" runat="server">
<div class="popup_large">
<asp:Label ID="Label7" Text="Floor Plan" runat="server" stle="float:left"></asp:Label>
<asp:ImageButton ID="ImageButton1" runat="server" ToolTip="No" ImageUrl="~/Images/no.png" Style="float: right; margin-right: 20px" />
<br />
<asp:ImageButton ID="img" runat="server" Height="30em" Width="45em" />
</div>
</asp:Panel>
</div>
</ContentTemplate>
</asp:UpdatePanel>
Here is a link to an example that adds to the background onclick to close the modal:
http://forums.asp.net/t/1528820.aspx
Copied the key bits here for reference:
function pageLoad() {
var mpe = $find("MPE");
mpe.add_shown(onShown);
}
function onShown() {
var background = $find("MPE")._backgroundElement;
background.onclick = function() { $find("MPE").hide(); }
}
<AjaxToolKit:ModalPopupExtender ID="mdlPopup" BehaviorID="MPE" runat="server"
TargetControlID="btnShowPopup" PopupControlID="pnlPopup"
CancelControlID="btnClose" BackgroundCssClass="modalBackground" />
C#
<AjaxToolKit:ModalPopupExtender .... BackgroundCssClass="jsMpeBackground" />
JavaScript (using jQuery)
jQuery('.jsMpeBackground').click(function () {
var id = jQuery(this).attr('id').replace('_backgroundElement', '');
$find(id).hide();
});
I had to do it this way so that I was able to click the actual popup without it closing, as I have functional user controls such as tab sections and textboxes on the popup.
<script type="text/javascript">
//Hide's Doc Center when clicking outside
function pageLoad(sender, args) {
if (!args.get_isPartialLoad()) {
$addHandler($find("MPE")._backgroundElement, "click", closePopup);
}
}
function closePopup(e) {
$find("MPE").hide();
}
//End
</script>
Now just make sure your BehaviorID in your actual ModelPopupExtender matches up with the tag above. Like so:
<ajaxToolkit:ModalPopupExtender ID="Popup" runat="server" PopupControlID="Container" BehaviorID="MPE" TargetControlID="fakeTargetControl" BackgroundCssClass="modalBackground" CancelControlID="btnCancel" />
Basically I think this just handles the 'click' event of the _backgroundElement attr of the modal popup, and on that event runs the closePopup() function.
write a dynamically created script that is added, in my example, when the modal popup extender is loaded. Note: In order to bind this event handler to the ModalPopupExtender.OnLoad event, you need to add a reference (in client-side code, you can add 'OnLoad="mpeExample_Load"' to your ModalPopupExtender tag).
protected void mpeExample_Load(object sender, EventArgs e) {
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"hideModalPopupViaClient", String.Format(#"function hideModalPopupViaClient() {
{
var modalPopupBehavior = $find('{0}');
if (modalPopupBehavior) modalPopupBehavior.hide();}}",
mpeExample.ClientID), true);
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "pageLoad", String.Format(#"function pageLoad() {
{
var backgroundElement = $get('{0}_backgroundElement');
if (backgroundElement) $addHandler(backgroundElement, 'click', hideModalPopupViaClient);
}}",
mpeExample.ClientID), true);}
I am working on Payment page and i want to show a popup for showing message your payment is processing. so for now i am using CustomValidator and Submit Button. and i want to show this popup when Args is valid. my code is.
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="" OnServerValidate="CustomValidator1_ServerValidate"
EnableClientScript="true" ValidationGroup="Authorize"></asp:CustomValidator>
<asp:Button ID="SubmitButton" runat="server" Text="Pay now" CausesValidation="true" CssClass="blue paynow" style="width:200px;"
ValidationGroup="Authorize" OnClick="SubmitButton_Click" OnClientClick="validate(ContentPlaceHolder1_chk_agree);" />
One better approach is to go with "updateProgress".
Place your submit button inside a updatePanel and place a loading gif image inside updateProgress which will show below loading image when payment progress is going on and will close automatically when payment is complete.
Loading ....
<asp:UpdateProgress id="updateProgress" runat="server">
<ProgressTemplate>
<asp:Image ID="imgUpdateProgress" runat="server" ImageUrl="~/images/loadingNew.gif" AlternateText="Loading ..." ToolTip="Loading ..."/>
</ProgressTemplate>
</asp:UpdateProgress>
To show a message box after validation, you can do the following:
Add the following javascript to your <head>
<script language="javascript">
function SubmitButton_ClientClick()
{
bool isValid = Page_ClientValidate("Authorize"); //triggers validation
if (isValid)
{
alert('Your payment is processing');
}
return isValid;
}
</script>
Then, change your button like this:
<asp:Button ID="SubmitButton" runat="server" Text="Pay now" CausesValidation="true"
CssClass="blue paynow" style="width:200px;"
ValidationGroup="Authorize" OnClick="SubmitButton_Click"
OnClientClick="return SubmitButton_ClientClick();" />
An even better approach is to use a popup div - here is a very basic example:
Add this somewhere in your <body>
<div id="popup_box" style="height:300;width:300;position:absolute;top:150;left:350;border:3px solid red;background:#d8d8d8;display:none;">
<h1>Payment is processing</h1>
<button id="popupBoxClose" onclick="document.getElementById("popup_box").style.display = 'none';">Close</button>
</div>
And modify the SubmitButton_ClientClick like this:
function SubmitButton_ClientClick()
{
bool isValid = Page_ClientValidate("Authorize"); //triggers validation
if (isValid)
{
document.getElementById("popup_box").style.display = '';
}
return isValid;
}